Should we synchronize run() method?

Here in this tutorial we will discuss whether we should synchronize the run() method or not. Another question may arise can we synchronize run() method? In simple word, yes, we can synchronize the run() method.

Do we need to synchronize the run method? When it comes to whether we need to synchronize or not, then it is not necessary to synchronize the run() method as this method gets executed by a single thread only.

Do we need to share the Runnable instance among multiple threads? If not, then Synchronizing the run() method of Runnable is completely pointless. Even if you apply synchronization to run() method, it means that you want to execute the threads in sequence and it’s a contradiction of the terms.

If we need to synchronize multiple threads, or we need a thread-safe queue, we can synchronize non-static method of other class because the method will be invoked by multiple threads or we can use more appropriate components, such as ConcurrentLinkedQueue. Therefore it’s not useful to use the synchronized keyword on run() method.

Synchronizing run() method is not effective for the following reasons:

  • Synchronization does not help if threads are created using separate Runnable instances.
  • Multi-threading environment does not occur if all threads are created using the same Runnable instances. So all instances will be executed sequentially not parallel.

Hope you got an understading why we do not need to use synchronized keyword on run() method.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *