Skip to main content

Wait/Notify Idiom


Some times threads need some condition to be realized by other threads to continue execution. Until this condition is realized a thread should make continues wait and check. But this means waste of resources and since thread probably owns lock that is needed by other threads to realize this condition, may lead to deadlocks. Java has a better alternative.  Java Object class has wait/notify/notifyAll methods to deal with such situations.  A complete example of wait/notify idiom is given below.

class ProducerConsumer {
    List dataList = new ArrayList();
    boolean empty = true;

    synchronized void produce() {
        dataList.add(new Object());
        empty = false;

        notifyAll();// notify waiting threads
    }

    synchronized void consume() {
        while (empty)
            try {
                wait(); // wait until notifyAll is called
            } catch (InterruptedException e) {}

        dataList.clear();// just clear list
        empty = true;
    }

    public static void main(String[] args) {
        final ProducerConsumer prodCons = new ProducerConsumer();
        // producer thread
        new Thread(
                new Runnable() {
                    public void run() {
                        while (true)
                            prodCons.produce();
                    }
                }
        ).start();

        // consumer thread
        new Thread(
                new Runnable() {
                    public void run() {
                        while (true)
                            prodCons.consume();
                    }
                }
        ).start();
    }
}

Assume consumer thread enters consume method and sees that empty flag is set. It calls wait on the object it has the lock of. When a thread calls wait method it releases the locks it owns and suspends execution by entering WAITING state until it is notified. Then producer thread enters produce method. Adds an arbitrary object to data list and clears empty flag. Then calls notifyAll on the object it has the lock of. All threads waiting on the lock of the object are waken up but only one of them will be able to resume execution. Other threads, if there are any, will continue waiting untill another notification is sent. Resuming thread will continue its execution from the point it left.

This way, threads are coordinated and achieved to work in harmony.

Things to Note:
-          Always check for condition inside a loop. Because notify may be sent for different conditions other than thread is waiting for.
-          Always call wait/notify/notifyAll methods within syncronized methods or statements. Other wise IllegalMonitorStateException will be thrown.
-          To wait/notify mechanism to work correctly threads must be owning the lock of the same object.

-          Notify method only wakes up a single thread, notiftAll on the other hand wakes up all waiting threads (of course only all threads waiting on the lock of the object notify is called). What happens if notify wakes up a single thread and this thread is waiting for a different condition to be realized? It will continue waiting and notification will be wasted. To avoid such waste, prefer notifyAll method.

Comments

Popular posts from this blog

Obfuscating Spring Boot Projects Using Maven Proguard Plugin

Introduction Obfuscation is the act of reorganizing bytecode such that it becomes hard to decompile. Many developers rely on obfuscation to save their sensitive code from undesired eyes. Publishing jars without obfuscation may hinder competitiveness because rivals may take advantage of easily decompilable nature of java binaries. Objective Spring Boot applications make use of public interfaces, annotations which makes applications harder to obfuscate. Additionally, maven Spring Boot plugin creates a fat jar which contains all dependent jars. It is not viable to obfuscate the whole fat jar. Thus obfuscating Spring Boot applications is different than obfuscating regular java applications and requires a suitable strategy. Audience Those who use Spring Boot and Maven and wish to obfuscate their application using Proguard are the target audience for this article. Sample Application As the sample application, I will use elastic search synch application from my G...

Hadoop Installation Document - Standalone Mode

This document shows my experience on following apache document titled “Hadoop:Setting up a Single Node Cluster”[1] which is for Hadoop version 3.0.0-Alpha2 [2]. A. Prepare the guest environment Install VirtualBox. Create a virtual 64 bit Linux machine. Name it “ubuntul_hadoop_master”. Give it 500MB memory. Create a VMDK disc which is dynamically allocated up to 30GB. In network settings in first tab you should see Adapter 1 enabled and attached to “NAT”. In second table enable adapter 2 and attach to “Host Only Adaptor”. First adapter is required for internet connection. Second one is required for letting outside connect to a guest service. In storage settings, attach a Linux iso file to IDE channel. Use any distribution you like. Because of small installation size, I choose minimal Ubuntu iso [1]. In package selection menu, I only left standard packages selected.  Login to system.  Setup JDK. $ sudo apt-get install openjdk-8-jdk Install ssh and pdsh, if...

Java Thread States

Java Threads may have 6 states: new , runnable , terminated , blocked , waiting , timed_waiting . When a thread is created it is in new state. When start method of thread is called it enters runnable state. Runnable state has two inner states: ready and running . If thread is eligible for execution it is said to be ready, if it is executing it is in running state. Remember calling start method on a already started thread will raise IllegalThreadStateException. When thread finishes its execution it enters into terminated state. When a thread is trying to access a resource, a synchronized statement for example, and it is not available, lock of the object is already acquired for example, it is blocked and said to be in blocked state. When lock is released an thread has chance to acquire lock it goes back to runnable state. When a thread calls join or wait method it enters into waiting state. When joined thread finishes or for wait method notify/notifyAll metho...