In this article Synchronization in Java we give the information about Synchronization in Java is a mechanism that allows only one thread to access a shared resource (such as an object, variable, or file) at a time.

Synchronization in Java:

Introduction

Synchronization in Java is a mechanism that allows only one thread to access a shared resource (such as an object, variable, or file) at a time.
It is mainly used in multithreading to ensure that multiple threads do not modify the same resource simultaneously, which helps in maintaining data consistency.

Why is Synchronization Necessary?

When two or more threads work on the same object concurrently, a problem known as a race condition or data inconsistency may occur.
Synchronization prevents such issues by allowing only one thread to execute a block of code or method at a time, thereby creating a thread-safe environment.

Types of Synchronization

  1. Synchronized Method

  • The synchronized keyword is used to make a method synchronized.
  • Only one thread can execute a synchronized method of an object at any given time.

Example:

class Table {

synchronized void printTable(int n) {

for (int i = 1; i <= 5; i++) {

System.out.println(n * i);

try {

Thread.sleep(400);

} catch (Exception e) {

System.out.println(e);

}

}

}

}

class MyThread1 extends Thread {

Table t;

MyThread1(Table t) { this.t = t; }

public void run() { t.printTable(5); }

}

class MyThread2 extends Thread {

Table t;

MyThread2(Table t) { this.t = t; }

public void run() { t.printTable(100); }

}

public class TestSynchronization {

public static void main(String args[]) {

Table obj = new Table();

MyThread1 t1 = new MyThread1(obj);

MyThread2 t2 = new MyThread2(obj);

t1.start();

t2.start();

}

}

Output Behavior:
Both threads do not alternate in their output because the synchronized method allows only one thread to execute at a time.

  1. Synchronized Block

  • A synchronized block is used when you need to synchronize only a specific portion of a method instead of the whole method.

Syntax:

synchronized(object) {

// synchronized code

}

Example: Odd–Even Program Using Synchronized Block

class Printer {

void printNumbers(String type) {

synchronized (this) {

if (type.equals(“even”)) {

System.out.println(“Even numbers:”);

for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) {

System.out.println(i);

try { Thread.sleep(300); } catch (Exception e) {}

}

}

} else {

System.out.println(“Odd numbers:”);

for (int i = 1; i <= 10; i++) {

if (i % 2 != 0) {

System.out.println(i);

try { Thread.sleep(300); } catch (Exception e) {}

}

}

}

}

}

}

class OddThread extends Thread {

Printer p;

OddThread(Printer p) { this.p = p; }

public void run() { p.printNumbers(“odd”); }

}

class EvenThread extends Thread {

Printer p;

EvenThread(Printer p) { this.p = p; }

public void run() { p.printNumbers(“even”); }

}

public class SyncOddEven {

public static void main(String[] args) {

Printer p = new Printer();

OddThread t1 = new OddThread(p);

EvenThread t2 = new EvenThread(p);

t1.start();

t2.start();

}

}

Output Behavior:
Both threads share the same Printer object. The synchronized block ensures that one thread completes printing before the other begins.

3. Static Synchronization

  • When a static method is synchronized, the lock is applied at the class level rather than the object level.
  • This means only one thread can access any static synchronized method of that class at a time.

Example: Static Synchronization using Area of Rectangle

class AreaCalculator {

synchronized static void calculateArea(int length, int width) {

System.out.println(“Calculating area for: ” + length + ” x ” + width);

int area = length * width;

try {

Thread.sleep(500);

} catch (Exception e) {

System.out.println(e);

}

System.out.println(“Area = ” + area);

System.out.println(“————————–“);

}

}

class MyThread1 extends Thread {

public void run() { AreaCalculator.calculateArea(5, 3); }

}

class MyThread2 extends Thread {

public void run() { AreaCalculator.calculateArea(7, 4); }

}

class MyThread3 extends Thread {

public void run() { AreaCalculator.calculateArea(10, 2); }

}

public class StaticSyncArea {

public static void main(String[] args) {

MyThread1 t1 = new MyThread1();

MyThread2 t2 = new MyThread2();

MyThread3 t3 = new MyThread3();

t1.start();

t2.start();

t3.start();

}

}

Output Behavior:
Even though multiple threads are started, only one thread executes the calculateArea() method at a time because the lock is at the class level.

Lock Concept

  • Every object in Java has an associated monitor lock (also called an object lock).
  • When a thread enters a synchronized method or block, it acquires the lock on that object.
  • Other threads must wait until the first thread releases the lock.

Key Points

  • Synchronization may reduce performance because it adds overhead to manage locks.
  • Use synchronization only when necessary, i.e., when threads share resources.
  • Always design synchronization carefully to avoid deadlocks.

Conclusion

The main purpose of synchronization in Java is to ensure data consistency and thread safety in a multithreading environment.
It ensures that only one thread can access the critical section of code at a time, thus preventing race conditions and ensuring reliable program execution.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Leave a Reply

Your email address will not be published. Required fields are marked *