In this article Synchronization methods in multithreading we give the information about Synchronization is used during multithreading in Java to ensure that multiple threads do not access the same resource (such as a shared object) simultaneously, which can lead to data inconsistency.

Synchronization methods in multithreading:

Synchronization is used during multithreading in Java to ensure that multiple threads do not access the same resource (such as a shared object) simultaneously, which can lead to data inconsistency. Synchronization is a control mechanism that allows only one thread to enter the critical section at a time.

There are three major methods of synchronization:

  1. wait()
  2. notify()
  3. notifyAll()

All these methods belong to the Object class and are used for interthread communication in multithreading.

Synchronization:

When multiple threads access a shared resource, it needs to be “synchronized” so that only one thread can access that resource at a time. For this, the synchronized keyword is used in Java.

By synchronization you can ensure that only one thread will work on the critical section at a time, thereby maintaining the security of data.

Synchronized Block and Method:

  • Synchronized method: If you want to synchronize an entire method, you can declare it with the synchronized keyword.
  • Synchronized block: If you only want to synchronize a small part of the code, then synchronized block can be used.

// synchronized method

public synchronized void myMethod() {

    // Critical section code

}

// Synchronized block

public void myMethod() {

    synchronized(this) {

        // Critical section code

    }

}

About wait(), notify(), and notifyAll() (Inter-thread Communication):

  1. wait() method:

This method blocks the current thread until notify() or notifyAll() method is called by another thread.

It is used with synchronization and should always be called inside a synchronized block or method.

When a thread calls wait(), it releases the lock it was holding, and goes on waiting for the monitor of that object.

synchronized(this)

{

    wait(); // close the thread

}

  1. notify() method:

  • This method alerts one of the threads that is paused due to the wait() method.
  • The notify() method resumes only one thread, and this thread can be random if multiple threads are in wait().
  • It is also called inside a synchronized block or method.

synchronized(this) {

    notify(); //will alert a stopped thread

}

  1. notifyAll() method:

This method alerts all threads that are paused due to wait() method.

After notifyAll() method all paused threads will compete for the monitor, and one will get the monitor and proceed.

synchronized(this) {

    notifyAll(); // will alert all stopped threads

}

wait(), notify(), notifyAll() // Example of using:

class SharedResource {

    synchronized void waitForTask() {

        try {

            System.out.println(Thread.currentThread().getName() + ” waiting…”);

            wait(); // The thread will stop here until notify() happens

            System.out.println(Thread.currentThread().getName() + ” resumed…”);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    synchronized void completeTask() {

        System.out.println(Thread.currentThread().getName() + ” notifying…”);

        notify(); // will alert a stopped thread

    }

}

public class WaitNotifyExample {

    public static void main(String[] args) {

        SharedResource resource = new SharedResource();

        // Thread 1

        new Thread(() -> {

            resource.waitForTask();

        }, “Thread 1”).start();

        // Thread 2

        new Thread(() -> {

            try {

                Thread.sleep(1000); // Start Thread 2 a little late

                resource.completeTask(); // notify a thread

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }, “Thread 2”).start();

    }

}

In this example:

Thread 1 calls the wait() method and stays on the monitor.

Thread 2 calls the notify() method after one second, which returns Thread 1 to the monitor and resumes it.

Summary:

  1. Synchronization is used to allow only one thread to access shared resources at a time.
  2. The wait() method pauses a thread until notify() or notifyAll() is called.
  3. The notify() method resumes a paused thread.
  4. The notifyAll() method makes all paused threads aware so they can compete for the monitor.

All three of these methods are used in multithreading for efficient interthread communication.

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

Join Now: Data Warehousing and Data Mining 

Leave a Reply

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