Synchronized Methods vs Synchronized Blocks - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Tuesday, September 05, 2017

Synchronized Methods vs Synchronized Blocks


Thread Synchronization

Java provides synchronized keyword to provide capabilities on controlling the access to shared resources for multiple threads. However this synchronization can be used in different formats,

  • Synchronized Methods
  • Synchronized Blocks
It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.

Synchronized Methods

An entire method can be marked as synchronized  resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.

Steps
  1. A thread access the synchronized  method. It implicitly acquires the lock and execute the code.
  2. If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released. 

Synchronized Blocks

To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste. 

More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.

Key Points

  1. Synchronized Block doesn't obtain a lock on a code block. It does acquire an lock on an object reference. The lock is kept until the defined statement is executed.
  2. Synchronized Method Synchronized Block clearly defines how the locking is provided but in synchronized blocks a deeper lookup is needed to understand the locking behavior.

Reference