permaculture playing cards
The moose likes Threads and Synchronization and the fly likes Several Threads working on same object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Several Threads working on same object" Watch "Several Threads working on same object" New topic

Several Threads working on same object

M Bryan
Ranch Hand

Joined: Jun 15, 2011
Posts: 64
Hi there,

i am working on a project where i am reading out several xml files. Sometimes it takes a while for a server to respone, so i am creating several thread and in each of them i am reading one xml file.
I already found the class CountDownLatch to count how many threads are already done and go on if all of them are done. But now i want to change the behaviour of code:
Let's say i am trying to read out five xml files and counting things in each file. If after having read two files i have found enough of the things i am looking for, i don't need the response of the other three. How can i stop all the threads at once from inside one of the thread done?

Thank you
Edward Harned
Ranch Hand

Joined: Sep 19, 2005
Posts: 291

The easiest way is to set the CountDownLatch to zero in the thread that wants the others ignored. Then the await() returns immediately. You'll have to inquire about the results thereafter.

The hard way is to pass a reference of all the other threads to each thread so one can "interrupt" the others.

I'm sure with a little work you can come up with your own method.

Ed's latest article: A Java Reactive Generator
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3733

You probably should not try to stop the working threads from the inside one of them. That's going to be very messy. Instead, the thread which spawned the workers and waits for their results can then (when the wait ends) interrupt all of the remaining threads to stop wasting their effort once the required number of "things" is recovered. That can be done manually, but you might be interested in using Java's built-in support for this kind of tasks, such as Executors.

To stop the threads at the right time, you could set the CountDownLatch initial count to the number of "things" that need to be recovered and in each thread decrease it with every processed "thing". That way the wait will end as soon as your worker threads together accumulate enough "things".
I agree. Here's the link:
subject: Several Threads working on same object
It's not a secret anymore!