How do threads that rely on one another communicate in Java?
For example, I am building a web crawler with threads that need data that comes from other threads.
How do threads that rely on one another communicate in Java?
For example, I am building a web crawler with threads that need data that comes from other threads.
That depends on the nature of the communication.
The simplest and most advisable form of inter-thread communication is simply to wait for the completion of other threads. That's most easily done by using Future
s:
ExecutorService exec = Executors.newFixedThreadPool(50);
final Future f = exec.submit(task1);
exec.submit(new Runnable() {
@Override
public void run() {
f.get();
// do stuff
}
});
The second task won't execute until the first completes.
Java 5+ has many concurrent utilities for dealing with this kind of thing. This could mean using LinkedBlockingQueue
s, CountDownLatch
or many, many others.
For an in-depth examination of concurrency Java Concurrency in Practice is a must-read.
Take a look at java.util.Observer/java.util.Observable. They are exactly what you are looking for.
You could use 2 ExecutorServices, submit a Callable implementation to service A that knows about follow on service B. When the Callable has completed it's work, it submits a new task to service B that does something additional with the results.
You could use a CountDownLatch or some other barrier if you need to perform additional work once all items have been processed in both services.
The ExecutorService api is pretty straight forward, for the most part you'll probably be using something like .newFixedThreadPool(int threads) and submitting Runnables/Callables to it.