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?
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".