user1047088
user1047088

Reputation:

Stopping application when all threads are died

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 ?

Upvotes: 2

Views: 177

Answers (6)

solendil
solendil

Reputation: 8458

This might be an answer to your problem: threads can be flagged as daemons. A daemon thread will not prevent the JVM from shutting down. So in your case, keep the worker threads "as is" and the less important threads as daemon with the thread.setDaemon(true) method.

Upvotes: 0

Mat
Mat

Reputation: 206755

Change that whole thing to:

for (Thread oneThread : threadsList) {
   try {
      oneThread.join();
   } catch (InterruptedException ie) {
      // handle this
   }
}

This will wait for each of the threads to finish their processing, but not waste CPU cycles. (The thread running this will sleep during the join.)

Upvotes: 1

dogbane
dogbane

Reputation: 274660

Use Thread.join like this:

for (Thread t : threadsList) {
    t.join();
}

Let's say you put this code at the end of your main method. Calling t.join() will cause the main thread to wait until thread t has died.

Upvotes: 2

Grim
Grim

Reputation: 1996

Usually the application quits automatically. Whatever:

System.exit(0); // forces the app to exit.

Upvotes: -1

SingleShot
SingleShot

Reputation: 19131

When you create a thread you can specify whether it is a "daemon" thread or not. When main() returns the application will continue running if there are any non-daemon threads running, however it will not continue running if only daemon threads remain. When you spawn your non-important thread you can spawn them as daemon threads which may achieve what you want.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340783

Mark all non-important threads as daemon threads (see: Thread.setDaemon()) and start all important ones normally.

Once all non-daemon threads are dead/done, the JVM quits automatically.

Upvotes: 4

Related Questions