Intent registration / login service in the application.

@Override protected void onHandleIntent(Intent intent) { try { // ЗАЧЕМ ? synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken( getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] if (intent.getStringExtra("state").equals("registration")) { //make registration request with callback } else if (intent.getStringExtra("state").equals("login")) { //make login request with callback } subscribeTopics(token); // [END register_for_gcm] } } catch (Exception e) { } } 

Questions:

  1. Why is synchronized() used here?
  2. What is generally need synchronized() , where to use it?

I read about multithreading, but did not really understand what and how. I would be happy to explain in simple words.

  • To avoid such questions, you need to read the basics of Java. - Vladyslav Matviienko

2 answers 2

In simple words: if you have variables that change in one of the threads, and are read in another, then their use must be synchronized . That is, enclose their use in a synchronized block.

The use of a synchronized block excludes the simultaneous execution of these blocks (synchronized on the same object) by different threads.


Why exactly synchronized is used here - most likely, some part of the code inside works with shared variables.

  • Thanks for the explanation! - researcher
  • @researcher: Please! - VladD

In your example, the synchronized block is used to make the code inside the block thread-safe, i.e. if this code is already running in some thread, then another thread will not be able to start executing this code until the previous thread has completed execution.

Details on synchronization and multithreading are best read in the official java documentation.