Stopping application when all threads are died - java

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 daemon threads (see: Thread.setDaemon()) and start all important ones normally.
Once all non-daemon threads are dead/done, the JVM quits automatically.

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.

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.)

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.

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.

Usually the application quits automatically. Whatever:
System.exit(0); // forces the app to exit.

Related

Unable to leave the loop with thread [duplicate]

Can anybody tell me what daemon threads are in Java?
A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
You can use the setDaemon(boolean) method to change the Thread daemon properties before the thread starts.
A few more points (Reference: Java Concurrency in Practice)
When a new thread is created it inherits the daemon status of its
parent.
When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:
finally blocks are not executed,
stacks are not unwound - the JVM just exits.
Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.
All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.
public class DaemonTest {
public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending") ;
}
}
class WorkerThread extends Thread {
public WorkerThread() {
// When false, (i.e. when it's a non daemon thread),
// the WorkerThread continues to run.
// When true, (i.e. when it's a daemon thread),
// the WorkerThread terminates when the main
// thread or/and user defined thread(non daemon) terminates.
setDaemon(true);
}
public void run() {
int count = 0;
while (true) {
System.out.println("Hello from Worker "+count++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
}
}
Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.
A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon() method on Thread.
Have a read of Daemon threads.
Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
For example, the HotJava browser uses up to four daemon threads named "Image Fetcher" to fetch images from the file system or network for any thread that needs one.
Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.
setDaemon(true/false) ? This method is used to specify that a thread is daemon thread.
public boolean isDaemon() ? This method is used to determine the thread is daemon thread or not.
Eg:
public class DaemonThread extends Thread {
public void run() {
System.out.println("Entering run method");
try {
System.out.println("In run Method: currentThread() is" + Thread.currentThread());
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException x) {}
System.out.println("In run method: woke up again");
}
} finally {
System.out.println("Leaving run Method");
}
}
public static void main(String[] args) {
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) {}
System.out.println("Leaving main method");
}
}
OutPut:
C:\java\thread>javac DaemonThread.java
C:\java\thread>java DaemonThread
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method
C:\j2se6\thread>
daemon: d(isk) a(nd) e(xecution) mon(itor) or from de(vice) mon(itor)
Definition of Daemon (Computing):
A background process that handles requests for services such as print spooling and file transfers, and is dormant when not required.
—— Source: English by Oxford Dictionaries
What is Daemon thread in Java?
Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.
Daemon threads are threads that run intermittently in the background as long as other non-daemon threads are running.
When all of the non-daemon threads complete, daemon threads terminates automatically.
Daemon threads are service providers for user threads running in the same process.
The JVM does not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is created by us.
Daemon threads acts as services in Windows.
The JVM stops the daemon threads when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement, for example, a monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped.
A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops.
One misconception I would like to clarify:
Assume that if daemon thread (say B) is created within user thread (say
A); then ending of this user thread/parent thread (A) will not end
the daemon thread/child thread (B) it has created; provided user thread is the only
one currently running.
So there is no parent-child relationship on thread ending. All daemon threads (irrespective of where it is created) will end once there is no single live user thread and that causes JVM to terminate.
Even this is true for both (parent/child) are daemon threads.
If a child thread created from a daemon thread then that is also a daemon thread. This won't need any explicit daemon thread flag setting.
Similarly if a child thread created from a user thread then that is also a user thread, if you want to change it, then explicit daemon flag setting is needed before start of that child thread.
Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.
Java has a special kind of thread called daemon thread.
Very low priority.
Only executes when no other thread of the same program is running.
JVM ends the program finishing these threads, when daemon threads are
the only threads running in a program.
What are daemon threads used for?
Normally used as service providers for normal threads.
Usually have an infinite loop that waits for the service request or performs the tasks of the thread.
They can’t do important jobs. (Because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. )
A typical example of these kind of threads is the Java garbage collector.
There's more...
You only call the setDaemon() method before you call the start() method. Once the thread is running, you can’t modify its daemon status.
Use isDaemon() method to check if a thread is a daemon thread or a user thread.
In Java, Daemon Threads are one of the types of the thread which does not prevent Java Virtual Machine (JVM) from exiting.
The main purpose of a daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.
By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.
Daemon threads are like assistants. Non-Daemon threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.
Here is an example to test behavior of daemon threads in case of jvm exit due to non existence of user threads.
Please note second last line in the output below, when main thread exited, daemon thread also died and did not print finally executed9 statement within finally block. This means that any i/o resources closed within finally block of a daemon thread will not be closed if JVM exits due to non existence of user threads.
public class DeamonTreadExample {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
int count = 0;
while (true) {
count++;
try {
System.out.println("inside try"+ count);
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("finally executed"+ count);
}
}
});
t.setDaemon(true);
t.start();
Thread.currentThread().sleep(10000);
System.out.println("main thread exited");
}
}
Output
inside try1
finally executed1
inside try2
finally executed2
inside try3
finally executed3
inside try4
finally executed4
inside try5
finally executed5
inside try6
finally executed6
inside try7
finally executed7
inside try8
finally executed8
inside try9
finally executed9
inside try10
main thread exited
Daemon thread is just like a normal thread except that the JVM will only shut down when the other non daemon threads are not existing. Daemon threads are typically used to perform services for your application.
Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks.
Points to Note :
Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true).
Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
Difference between Daemon and Non Daemon thread in Java :
1) JVM doesn't wait for any daemon thread to finish before existing.
2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.
Daemon threads are as everybody explained, will not constrain JVM to exit, so basically its a happy thread for Application from exit point of view.
Want to add that daemon threads can be used when say I'm providing an API like pushing data to a 3rd party server / or JMS, I might need to aggregate data at the client JVM level and then send to JMS in a separate thread. I can make this thread as daemon thread, if this is not a mandatory data to be pushed to server.
This kind of data is like log push / aggregation.
Regards,
Manish
Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads.
example updating system for unix,unix is daemon process.
child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method.
so daemon thread or daemon process are basically responsible for managing resources.
for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory.
jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.
For me, daemon thread it's like house keeper for user threads.
If all user threads finished , the daemon thread has no job and
killed by JVM.
I explained it in the YouTube video.
Let's talk only in code with working examples. I like russ's answer above but to remove any doubt I had, I enhanced it a little bit. I ran it twice, once with the worker thread set to deamon true (deamon thread) and another time set it to false (user thread). It confirms that the deamon thread ends when the main thread terminates.
public class DeamonThreadTest {
public static void main(String[] args) {
new WorkerThread(false).start(); //set it to true and false and run twice.
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending");
}
}
class WorkerThread extends Thread {
boolean isDeamon;
public WorkerThread(boolean isDeamon) {
// When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
this.isDeamon = isDeamon;
setDaemon(isDeamon);
}
public void run() {
System.out.println("I am a " + (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));
int counter = 0;
while (counter < 10) {
counter++;
System.out.println("\tworking from Worker thread " + counter++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
System.out.println("\tWorker thread ends. ");
}
}
result when setDeamon(true)
=====================================
I am a Deamon Thread
working from Worker thread 0
working from Worker thread 1
Main Thread ending
Process finished with exit code 0
result when setDeamon(false)
=====================================
I am a User Thread (none-deamon)
working from Worker thread 0
working from Worker thread 1
Main Thread ending
working from Worker thread 2
working from Worker thread 3
working from Worker thread 4
working from Worker thread 5
working from Worker thread 6
working from Worker thread 7
working from Worker thread 8
working from Worker thread 9
Worker thread ends.
Process finished with exit code 0
Daemon threads are generally known as "Service Provider" thread. These threads should not be used to execute program code but system code. These threads run parallel to your code but JVM can kill them anytime. When JVM finds no user threads, it stops it and all daemon threads terminate instantly. We can set non-daemon thread to daemon using :
setDaemon(true)
Daemon threads are threads that run in the background as long as other non-daemon threads of the process are still running. Thus, when all of the non-daemon threads complete, the daemon threads are terminated. An example for the non-daemon thread is the thread running the Main.
A thread is made daemon by calling the setDaemon() method before the thread is started
For More Reference : Daemon thread in Java
There already are numerous answers; however, maybe I could shed a bit clearer light on this, as when I was reading about Daemon Threads, initially, I had a feeling, that I understood it well; however, after playing with it and debugged a bit, I observed a strange (to me) behaviour.
I was taught, that:
If I want the thread to die right after the main thread orderly finishes its execution, I should set it as Diamond.
What I tried:
I created two threads from the Main Thread, and I only set one of those as a diamond;
After orderly completing execution of the Main Thread, none of those newly created threads exited, but I expected, that Daemon thread should have been exited;
I surfed over many blogs and articles, and the best and clearest definition I found so far, comes from the Java Concurrency In Practice book, which very clearly states, that:
7.4.2 Daemon threads
Sometimes you want to create a thread that performs some helper
function but you don’t want the existence of this thread to prevent
the JVM from shutting down. This is what daemon threads are for.
Threads are divided into two types: normal threads and daemon threads.
When the JVM starts up, all the threads it creates (such as garbage
collector and other housekeeping threads) are daemon threads, except
the main thread. When a new thread is created, it inherits the daemon
status of the thread that created it, so by default any threads
created by the main thread are also normal threads. Normal threads and
daemon threads differ only in what happens when they exit. When a
thread exits, the JVM performs an inventory of running threads, and if
the only threads that are left are daemon threads, it initiates an
orderly shutdown. When the JVM halts, any remaining daemon threads are
abandoned— finally blocks are not executed, stacks are not unwound—the
JVM just exits. Daemon threads should be used sparingly—few processing
activities can be safely abandoned at any time with no cleanup. In
particular, it is dangerous to use daemon threads for tasks that might
perform any sort of I/O. Daemon threads are best saved for
“housekeeping” tasks, such as a background thread that periodically
removes expired entries from an in-memory cache.
JVM will accomplish the work when a last non-daemon thread execution is completed. By default, JVM will create a thread as nondaemon but we can make Thread as a daemon with help of method setDaemon(true). A good example of Daemon thread is GC thread which will complete his work as soon as all nondaemon threads are completed.
Daemon threads are those threads which provide general services for user threads (Example : clean up services - garbage collector)
Daemon threads are running all the time until kill by the JVM
Daemon Threads are treated differently than User Thread when JVM terminates , finally blocks are not called JVM just exits
JVM doesn't terminates unless all the user threads terminate. JVM terminates if all user threads are dies
JVM doesn't wait for any daemon thread to finish before existing and finally blocks are not called
If all user threads dies JVM kills all the daemon threads before stops
When all user threads have terminated, daemon threads can also be terminated and the main program terminates
setDaemon() method must be called before the thread's start() method is invoked
Once a thread has started executing its daemon status cannot be changed
To determine if a thread is a daemon thread, use the accessor method isDaemon()
Java daemon thread
[Daemon process]
Java uses user thread and daemon tread concepts.
JVM flow
1. If there are no `user treads` JVM starts terminating the program
2. JVM terminates all `daemon threads` automatically without waiting when they are done
3. JVM is shutdown
As you see daemon tread is a service thread for user treads.
daemon tread is low priority thread.
Thread inherits it's properties from parent thread. To set it externally you can use setDaemon() method before starting it or check it via isDaemon()
Daemon Thread
Threads that run in the background are called daemon threads.
Example of Daemon Threads:
Garbage Collector.
Signal Dispatcher.
Objective of Daemon Thread:
The main objective of the daemon threads is to provide support to the non-daemon threads.
Additional information about Daemon Thread:
Generally, Daemon threads run in the MIN_PRIORITY however, it is possible to run daemon threads with MAX_PRIORITY as well.
Example: Usually the GC runs with a MIN_PRIORITY priority, however, once there is a requirement for additional memory. JVM increases the priority of the GC from MIN_PRIORITY to MAX_PRIORITY.
Once the Thread has been started, it can't be changed from Daemon Thread to Non-Daemon Thread that will result in IllegalThreadStateException.
Example:
public static void main(String[] args) {
Thread.currentThread().setDaemon(true);
}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.setDaemon(Thread.java:1403)
If we are branching off a thread, the child thread inherits the nature of the parent thread. If the parent thread is a non-daemon thread automatically the child thread will be non-daemon as well and if the parent thread is a daemon, the child thread will be a daemon as well.
class Scratch {
public static void main(String[] args) {
CustomThread customThread = new CustomThread();
customThread.start();
}
}
class CustomThread extends Thread{
#Override
public void run() {
System.out.println(currentThread().isDaemon());
}
}
Output:
false
When the last non-daemon thread terminates, all the daemon threads get terminated automatically.
class Scratch {
public static void main(String[] args) {
System.out.println("Main Thread Started.");
CustomThread customThread = new CustomThread();
customThread.setDaemon(true);
customThread.start();
System.out.println("Main Thread Finished.");
}
}
class CustomThread extends Thread{
#Override
public void run() {
System.out.println("Custom Thread Started.");
try {
sleep(2000);
} catch (InterruptedException ignore) {}
System.out.println("Custom Thread Finished."); //Won't get executed.
}
}
Output:
Main Thread Started.
Main Thread Finished.
Custom Thread Started.
User threads versus Daemon threads in java threads
Daemon Threads
this threads in Java are low-priority threads that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread.
User Threads
this threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it
"keep in mind both User and Daemon threads wrapped upon OS threads"
Recently OpenJdk proposed Virtual threads with in project Loom (which they are User based as well) you may find more on Fibers and Continuations for the Java Virtual Machine threads in here.

How to stop / kill multiple threads after a Time-Out value in java

I want to stop / kill all Threads (Runnables) started by Main after a given timeout. I tried to do as mentioned below. But it is not working as expected. Apart from that, I tried with the Thread.interrupt() but the results is negative. I tried thread.stop(). It is working but deprecated.
Can anyone give some idea on this?
Note : I'm focusing on a solution for Runnables not Callables. And I'm trying to do this bymodifying only the client code (Main). Not the Threads (Supplier)
Main
Thread roxtoursThrd = new Thread(new Supplier("roxtours", 1));
Thread bluevacationsThrd = new Thread(new Supplier("bluevacations", 1));
Thread elixerThrd = new Thread(new Supplier("elixer", 1));
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
taskExecutor.execute(roxtoursThrd);
taskExecutor.execute(bluevacationsThrd);
taskExecutor.execute(elixerThrd);
taskExecutor.shutdown();
// taskExecutor.shutdownNow(); // This is also not stopping threads. They continue.
try {
taskExecutor.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Supplier.java
public class Supplier implements Runnable {
public Supplier(String name, int count) {
this.name = name;
this.count = count;
}
#Override
public void run() {
try {
// Some time consuming operations (URL Connections, XML Decoding, DB Queries etc etc) are goes in here.
} catch (Exception e) {
e.printStackTrace();
}
}
String name = null;
int count = 0;
Logger logger = Logger.getLogger(Supplier.class);
}
Making the executor's tasks respond to interruption will require changing the code for the Suppliers. Interruption is cooperative; the thread being interrupted gets a flag set on it, but it's up to the thread to decide how to handle it. If your Runnable doesn't act on it, as in your example, then nothing happens, the thread just keeps on executing.
The Executor can only cancel threads that respond to interruption, see the API documentation for ExecutorService.shutdownNow:
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
A thread can check its flag with the Thread#isInterrupted method. Your Runnable task should check Thread.getCurrentThread().isInterrupted().
If a thread is waiting or sleeping when the interrupted flag is set then an InterruptedException will be thrown and the flag will be cleared.
Do not use Thread#setDaemon(true) unless you're prepared for those threads to disappear suddenly with no warning and no chance to clean up pending tasks when the rest of the application shuts down.
The other option is the deprecated Thread#stop method, which causes ThreadDeath to be thrown. Unlike interruption, this is not cooperative, and it's between difficult and impossible to write code that can predictably and cleanly terminate when this exception occurs, because ThreadDeath can be thrown anywhere, unlike InterruptedException, which is much more manageable since it is only thrown from specific blocking calls.
Use shutdownNow() instead of shutdown().
The shutdown() will initiate the shutdown and it will not accept any new tasks but you never know when the threads will be actually stopped.
The shutdownNow() will immediately attempts to stop all the active threads and this will return all the active threads which are awaiting for execution.
Again there is no guarantee that all the threads will be stopped immediately (Threads will go for a graceful shutdown and it may take time based on the task given to the thread). We have to use either of the below methods to wait till all the threads are completed its execution.
executor.awaitTermination(...);
or
while (! executor.isTerminated()) {
// Sleep for few milliseconds...
}
Refer the doc: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29
Your thread's run method is not blocking, hence it does not run into a situation where an InterruptedException is thrown.
When a Thread is inerrupted, besides throwing an exception if it is blocking, it also has its interrupted status set, that is to say the method Thread#isInterrupted() returns true. Also, the method Thread#interrupted also returns true, but with the latter the interrupted status of the thread is cleared.
In your example you are not blocking nor are you checking the threads inerrupted status.
EDIT: Since you are not checking to see if the thread is interupted nor are you blocking, then you can't stop the threads explicitly, but you can stop them by making them daemon threads and then when your main thread (which is a user thread) finishes, all the other daemon threads will stop. Main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution.
If you want to interrupt threads, you have to provide interruption entrance point. Sleep for a very short time, for example, then catch and handle InterruptionException.
Next what you can do is make use of isInterrupted() method in every iteration and the handle that as well.
Other approach would be to make all the threads daemons with setDaemon(), as they would be killed after main thread finishes, but this would be useful only if main was to be stopped.
In response to your edit/updated question:
excerpt from shutdownNow() documentation
There are no guarantees beyond best-effort attempts to stop processing
actively executing tasks. For example, typical implementations will
cancel via Thread.interrupt(), so any task that fails to respond to
interrupts may never terminate.
So either you prepare you application to work as multi-threaded or you stick to single thread.
Also, see How do you kill a thread in Java?.
And the most important link from the question above: http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

How does daemon thread survive after JVM exits?

I am reading docs about Java's setDaemon() method, and got confused when I read that JVM exits without waiting for daemon threads to finish.
However, since essentially daemon threads are Java Thread's, which presumably rely on running on JVM to achieve its functionalities, how do daemon threads even survive if JVM exits before the daemon thread finishes?
They don't survive. The JVM will exit when all the threads, except the daemon ones, have died.
When you start your application, the JVM will start a single, non-daemon thread to run your static main method.
Once the main method exits, this main thread will die, and if you spawned no other non-daemon thread, the JVM will exit.
If however you started another thread, the JVM will not exit, it will wait for all the non-daemon threads to die before exiting.
If that thread you spawned is doing something vital, this is absolutely the right thing to do, however often you have some threads that are not that vital, maybe they are listening to some external event that may or may not happen.
So, in theory, you should place some code somewhere to stop all the threads you spawned to allow the JVM to exit.
Since this is error prone, it's way easier to mark such non-vital threads as daemons. If they are marked as such, the JVM will not wait for them to die before exiting, the JVM will exit and kill those threads when the "main threads" (those not marked as daemon) have died.
To put it in code, it's something like this :
public class Spawner {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
System.out.println("I'm still alive");
}
}
});
// Try uncommenting/commenting this line
// t.setDaemon(true);
t.start();
System.out.println("Main thread has finished");
}
}
(I haven't tested this code, wrote it here directly, so it could contain stupid mistakes).
When running this code with the line commented, the thread is not deamon, so even if your main method has finished, you'll keep on having the console flooded until you stop it with CTRL+C. That is, the JVM will not exit.
If you uncomment the line, then the thread is a daemon, and soon after the main method has finished, the thread will be killed and the JVM will exit, without the need for CTRL+C.

Terminate Main Thread without ensuring the termination of threads spawned by it

I have implemented a multi-threaded program which involves spawning a thread for each user,and performing some minor activities(No exhaustive processes like database connection involved).The main thread runs infinitely,and its termination is handled via monitoring file creation activity.
My question is, is it okay to terminate the main thread straightaway,without waiting for the threads to finish ? (assuming that the threads would complete on their own(!),could be a false assumption).
Sure.
The main thread is just one thread amongst others and its termination won't affect the other threads (unless you don't use System.exit() to stop the thread...).
The main thread is just the first thread*) that has been started but it has no extra or hidden features or functionalities.
*) to keep it simple - the jvm may have started some internal threads before main - but the application has no code for those threads
Yes, The point of threads is that they run independently.
It would only matter if your client threads were started as daemon threads and main is the only non-daemon thread. (In which case, the application would shutdown when it stops)
Yes and usually that's the case in most applicaitons. The main thread usually is repsonibly for initiating the system and it can peacefully die after that.
Note that you don't really "terminate" themain thread, instead just let it complete its run method. And thats ok.

Is it bad for a java application to shutdown while a separate thread is sleeping?

For example if i have a java command line program that spawns a new thread (thread #2) to do some polling, and then sleep for 5 minutes. while the main thread (thread #1) of the program is running and then finishes before the 5 minutes from thread #2 is up, so the program will exit. Is there any problem with this? Should I interrupt Thread #2 in Thread #1 before the end of the main function in this program?
It may be considered bad practice and a sign of poor design by some, but in principal there shouldn't be any problem to terminate the JVM with System.exit. Not if there is no clean-up to be performed by Thread #2.
Another issue though, is whether or not Thread #2 may be in the middle of some action.
It depends entirely on what it's doing. When the program exits, the process will terminate, taking any additional threads with it. The only potential problem would be if Thread #2 holds some resource handle. However, if all it's doing is reading, then you shouldn't have a problem.
Non-deamon threads keep on running in the background after main has finished execution.
As a result you will have hunging threads unless you explicitly call System.exit which kills all threads.
The best approach though would be to stop the thread#2.
Just use a status flag e.g. boolean die in thread#2.
Thread#1 will interrupt the thread#2, thread#2 will then see the die flag (set by thread#1) set to true, will do any clean up necessary and exit gracefully.
In your case that thread#2 is just sleeping for 5 mins and not doing anything it will be fine.
Have a look at here.
For the termination of a java program, it is necessary for all non-daemon threads to terminate first.
Once all the non-daemon threads stop their execution, the JVM will kill off all the daemon threads and thus will get shut-down.
In you case, there should not be any problem, unless and until your Thread #2 is doing some important function like handling resources.

Categories

Resources