In my java application I have many threads, but there are several most important threads, which do complex calculations (accessing remote db’s, etc).
In case all these important threads are died, then I need to quit the application, even less important threads still are running.
I implemented an additional (thread) class to monitor these threads with core functionality like this:
boolean allThreadsDied;
do {
allThreadsDied = true;
for (Thread oneThread : threadsList) {
allThreadsDied = allThreadsDied & (!oneThread.isAlive());
}
} while (!allThreadsDied);
// now, it's time to quit the application
This thread runs permanently and checks the state of important threads.
I think I have invented a bicycle, and very non-efficient bicycle. Because this thread, running permanently, produces high processor load, even when there are no current calculations.
My question is as follows: is there a more efficient way to monitor a group of threads and get a signal when all these threads are died ?
Mark all non-important threads as
daemonthreads (see:Thread.setDaemon()) and start all important ones normally.Once all non-daemon threads are dead/done, the JVM quits automatically.