I’m running a method from my main that generates data and I also fork a thread that monitors a queue that the method is writing to and if there’s data it saves it to a disk.
My problem is in the past I would multi-thread it and was able to monitor the life of other threads but I’m not sure how to do that if its just the main method? The issue the method is generating data slowly and using sleep or !queue.empty() doesn’t work as as soon as it empties the queue the forked file writer process stops.
I know worst case I can write to the file in the method generating the data, but other than that is there anything I can do to monitor if another method is still being executed?
Sounds like a good job for an
ExecutorService. Create it in your main method:ExecutorServiceis basically a wrapper around a queue and a set of threads that are waiting on that queue (10 in example above). The moment something appears in the queue (is submitted), exactly one thread picks it up:Where
someWorkis a Runnable, that e.g. wraps data to be written to disk and writing procedure. When you are done in the main thread, you simply ask thepoolto terminate gracefully:This code will wait 60 seconds for other threads to finish and process all items in the queue.
Show us more code, I can assist you in refactoring it. If you don’t want to go that far, there are methods in some Java collections that block when the queue is empty and wake the thread when something appears.