Synchronized block

  • Eclipse: Oxygen
  • Java: 1.8

The synchronized block is the basic to synchronization for a certain code which needs to be synchronized. It means that there might be code where no need for synchronization, then due to applying the synchronized method on 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

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

Time required for thread 1 was:1877

Time required for thread 2 was:1977

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

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

Time required for thread 1 was:1901

Time required for thread 2 was:2001

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu