14.06. Synchronized block

Synchronized block

  • Eclipse: Oxygen
  • Java: 1.8

The synchronized block is the basic synchronization for a certain code that needs to be synchronized. It means that there might be code where no need for synchronization, then due to applying the synchronized method that the execution of the program is slowed down. Therefore, this problem is improved by a synchronized block.

In the following program, if you want to control the synchronization with a specific part of a method that will be synchronized with the object, specify a synchronized block.

Here we use the synchronized keyword in the method declaration, and synchronize the entire method with the class. Synchronized block construct takes method in parentheses.

In this program “this” is used to synchronize only the first part. Because we are making use of the synchronized block on the synchronized method. It reduces the scope of a lock, and the time required to execute both threads.

Output

Synchronized block on an object

Whenever we make use of synchronized, the monitor lock is applied. This feature can be used to hide the synchronized block from the outside world. It is recommended to make use of a private object in order to apply the lock.

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments