home page

Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.
Syntax to use synchronized block

Example of synchronized block

Let's see the simple example of synchronized block.

Program of synchronized block
Test it Now
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       

Same Example of synchronized block by using annonymous class:

//Program of synchronized block by using annonymous class
Test it Now
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500