Java — Synchronization Block | Code Factory

Code Factory
2 min readJun 1, 2020

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) {
---
}
of a thread got lock of current object then only it is called to execute this(---) area.

2. To get lock of particular object ‘a’

synchronized(b) {
---
}
of a thread got lock of particular object 'a' then only it is allowed to execute this(---) area.

3. To get class level lock

synchronized(Display.class) {
---
}
of a threat got class level lock of Display class, then only it is allowed to execute this(---) area.

SynchronizedTest.java

package com.example.thread;/**
* @author code.factory
*
*/
public class SynchronizedTest {
public static void main(String... args) {
Display d = new Display();
MyThread t1 = new MyThread(d, "Code");
MyThread t2 = new MyThread(d, "Factory");
t1.start();
t2.start();
}
}
class Display {
public void display(String name) {
// lines of code
synchronized (this) {
for(int i=1; i<=5; i++) {
System.out.print("Hello ");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
// lines of code
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.display(name);
}
}

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) {
---
}
CE :
error: unexpected type
synchronized (i) {
^
required: reference
found: int
1 error

--

--