garbagecollector
garbagecollector

Reputation: 3880

How to signal the caller thread that ExecutorService has finished a task

From the main thread:

executorService.submit(new Runnable() { ... });

Now when Runnable has finished executing, is there the Java's standard way of signaling the caller thread that it has finished executing, without making a new interface/listener class?

Bonus points if the signal can be emitted from the caller thread.

Upvotes: 4

Views: 2909

Answers (3)

John Kane
John Kane

Reputation: 4453

I am not sure of your implementation and how many threads will be running simultaneously, so this may not work. One thing you could take a look at is to have the runnable itsself signal it is completed by calling a method that knows how to update the UI component that is needed.

Upvotes: 0

Enno Shioji
Enno Shioji

Reputation: 26882

You can block on get() of the Future object that is returned, or poll the isDone() method on it. Alternatively, you could use the google guava library that has ListenableFuture.

Upvotes: 3

David Harkness
David Harkness

Reputation: 36562

submit returns a Future on which the submitting thread can call get to block until the task completes.

Future<?> future = executor.submit(new Runnable() { ... });
future.get();

Upvotes: 4

Related Questions