Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Multithreading -Wait/notifyAll Question

I have a class which spawns a bunch of threads and have to wait till all the spawned threads are completed. ( I need to calculate the time for all threads to complete).

The MainClass spawns all the threads and then it checks whether all the threads are completed before it can call itself completed.

Will this logic work. If so, is there a better way to do this? If not , I would like to better understand this scenario.

class MainClass{
    private boolean isCompleted;
    ...
    for(task : tasks){
        threadpool.execute(task);
    }

    for(task : tasks){
        if(!task.isCompleted()){
            task.wait()
        }
    }

    isCompleted = true;
}


class Task{
    public void run(){
        ....
        ....
        synchronized(this){
            task.completed = true;
            notifyAll();
        }
    }
}
like image 582
Vanchinathan Chandrasekaran Avatar asked Jun 09 '11 17:06

Vanchinathan Chandrasekaran


2 Answers

notifyAll() is relatively slow. A better way is to use CountDownLatch:

import java.util.concurrent.CountDownLatch;

int n = 10;
CountDownLatch doneSignal = new CountDownLatch(n);
// ... start threads ...
doneSignal.await();

// and within each thread:
doWork();
doneSignal.countDown();
like image 129
Thomas Mueller Avatar answered Oct 10 '22 00:10

Thomas Mueller


There's no need for wait/notify in this case. You can just loop through the threads and call join(). If the thread's already finished, the MainClass thread will just wait for the next one.

You might want to have a look at the higher-level utilities in the java.util.concurrent package too.

like image 31
artbristol Avatar answered Oct 10 '22 00:10

artbristol