Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Several Threads working on same object

 
M Bryan
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic