Abichellam
Abichellam

Reputation: 509

Thread Completion Notification

I have many threads that runs concurrently. In these few threads execution depends on the completion of other threads. For eg,

Thread - 1, Thread - 2, Thread - 3

These can run independently.

Thread - 4, depends on the completion of 1 and 2

Thread - 5, depends on the completion of 1 and 3

Thread - 6, depends in the completion of 1, 2, and 3

All the threads are submitted to the executor. Thread 4, 5, and 6 has to implement some waiting mechanism before starting. What are the possible blocking mechanisms available in java for the above situation.

Upvotes: 1

Views: 146

Answers (3)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

Proposals to use blocking facilities like CountDownLatch or Future can work on an unbounded Executor or at least able to start all 6 threads simultaneously, otherwise there is a risk of thread starvation. So using Executor has no advantage compared to starting all 6 threads directly, without an Executor.

Meanwhile, the dependencies dictate that no more than 3 threads will run at each moment of time. In case the actual number of threads matters, you should use event-driven facilities instead of blocking ones. What I mean is an object which collects signals and, when signals from both tasks 1 and 2 has arrived, submits task 4 etc. From theoretical point of view, this resembles Petri nets. Unfortunately, JDK does not provide standard classes for event-driven task coordination. It is not hard to implement such a signal collector/task emitter from scratch, or you can use dataflow library df4j.

Upvotes: 2

Sanchit
Sanchit

Reputation: 438

You may try to use the ExecutorService implementation of Threads for which on finishing the job (the tasks you want to accomplish with threads) you may try to invoke await() method of CountDownLatch class as follows:

public void finishWork() {
        try {
            System.out.println("START WAITING for thread");
            countDownLatch.await();
            System.out.println("DONE WAITING for thread");
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }

And to monitor each thread you may try to invoke countDown() method available from this class. So, before calling the shutdown() on ExecutorService (or, completing with the job with threads), the above method could be used.

Upvotes: 1

René Link
René Link

Reputation: 51483

You get a Future<T> obejct when you use

Future<?> ExecutorService.submit(Runnable task)

Just pass the future to the thread that must wait for the completion (e.g it's constructor) and do:

future.get();

which will block until the thread for this future has finished.

Upvotes: 3

Related Questions