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

Create your First Program in C Language

Setting Up A new Raspberry Pi (Raspberry Pi OS)

image

Cypress — A Game changer in Test Automation | Perfomatix | Full Stack Engineering Company

Decrease UI tests time execution

How to conduct a perfect sprint review (demo) — complete guide

Weekly Update| Ares Protocol airdrop activity worth 50,000 USDT is raging on

kruskal’s algorithm

The Ocean of Web applications and Tropical island of Jam.py

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

JAVA 16 And 17: Evolutions and new features — Part 2

Unit Testing Apache Camel

What is Server-Sent Events (SSE) and how to implement it?

Optimizing GC time by reducing Humongous allocations