Java — Synchronization Block | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • If very few lines of the code require Synchronization then it is not recommended to declare entire method as Synchronized, We have to enclose those few lines of the code by using Synchronized block.
  • The main advantage of Synchronized block over Synchronized method is it reduce waiting time of thread and improves performance of the system.
  • We can declare Synchronized block as follows.

1. To get lock of current object

synchronized(this) {
---
}

2. To get lock of particular object ‘a’

synchronized(b) {
---
}

3. To get class level lock

synchronized(Display.class) {
---
}

SynchronizedTest.java

package com.example.thread;

Output :

Hello Code
Hello Code
Hello Code
Hello Code
Hello Code
Hello Factory
Hello Factory
Hello Factory
Hello Factory
Hello Factory
  • Lock concept applicable for object types and class types but not for primitives. Hence we can’t pass primitive type as argument to synchronized block. Otherwise we will get CE saying unexpected type.
int i = 10;
synchronized(x) {
---
}