Java — Synchronization Block | Code Factory

  • 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.
synchronized(this) {
---
}
of a thread got lock of current object then only it is called to execute this(---) area.
synchronized(b) {
---
}
of a thread got lock of particular object 'a' then only it is allowed to execute this(---) area.
synchronized(Display.class) {
---
}
of a threat got class level lock of Display class, then only it is allowed to execute this(---) area.
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);
}
}
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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Hybrid vs Native Apps. When to use what?

Rough Start - What Happened?

Functional Testing Types-2

Do Your Stats Look Like This?

Medium is bad at tech support

EXACTLY WHAT YOU NEED TO KNOW TO BECOME A FRONT END DEVELOPER IN 2021

AWS CloudWatch Lambda Insights

JWT HttpOnly authorization with Laravel and React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Chain of Responsibility Pattern(Behavioral Design Pattern)

Undo Changes With Memento Pattern

Which implementation of Singleton Pattern do I need?

Different calling forms of REST services with Feign client in Spring Cloud