Skip to content

WaitForMultipleObject in java

May 10, 2012

I needed similar functionality as provided by above windows function. Searched around but did not find straight forward answer.To be exact I was looking for waiting on multiple threads and quit if any of them quit.

With this objective I looked into java.util.concurrent package and found CountDownLatch object provided by this package. Soon I found out this is what I was looking for.  Below is sample code which shows this functionality in action.

import java.util.concurrent.CountDownLatch;

class LatchDemo implements Runnable {
    private CountDownLatch latch = null;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        System.out.println(“runing thread:” + Thread.currentThread().getId());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println(“Interrupted thread:”
                    + Thread.currentThread().getId());
        }
        System.out.println(“Done with work:” + Thread.currentThread().getId());
        this.latch.countDown();
    }
}

public class WaitForMultiple {
    public static void main(String[] args) {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            Thread firstTh = new Thread(new LatchDemo(latch));
            firstTh.setDaemon(true);
            frist.start();
            //Thread.sleep(5000);
            Thread secondTh = new Thread(new LatchDemo(latch));
            secondTh.setDaemon(true);
            secondTh.start();
            System.out.println(“Waiting for latch”);
            latch.await();
            System.out.println(“Waiting complete”);
        } catch (InterruptedException e) {
        }
    }
}

ConntDownLatch is thread safe so you don’t need any other synchronization primitives. Although if any of thread dies main thread in above sample will come out of wait but if you want to quit the jvm when main thread complete it’s wait  you can set newly created thread as daemons by   setDaemon api.

Simple isn’t it:)

Advertisements

From → Tech

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: