Synchronized Block in Java

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

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases, we can use synchronized block.

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

Points to Remember

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.
  • A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource.
  • The system performance may degrade because of the slower working of synchronized keyword.
  • Java synchronized block is more efficient than Java synchronized method.

Syntax

Example of Synchronized Block

Let's see the simple example of synchronized block.

TestSynchronizedBlock1.java

Output:

       5
       10
       15
       20
       25
       100
       200
       300
       400
       500

Synchronized Block Example Using Anonymous Class

TestSynchronizedBlock2.java

Output:

Sending a Message: Hola 
Hola Sent
Sending a Message: Welcome to Javatpoint website 
Welcome to Javatpoint website Sent





Latest Courses