When does a typical Java app finish?
If I start a new thread in the main method and then the main method finishes, but the other thread continues working, the app would still be on until all it's threads have died, wouldn't it?
Thanks & Merry Christmas!
Yes, unless it's a deamon thread. Quoting from Thread API:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
The main() function defines your main user thread. You might have other user threads that you created as well. You might also have called setDeamon() on some of those threads.
The JVM will end when:
The main routine ends and there are no other non-deamon threads
You have an uncaught Exception in the main thread and there are no other non-deamon threads
System.exit() or Runtime.halt() is called
Internal JVM error (rare)
Kill -9 signal from OS
Power failure or similar non-recoverable hardware failure
Related
When do I actually need call this method Runtime.getRuntime().addShutdownHook() and when or why I need to shutdown my application. Could anyone please explain me this by giving some example.
Thanks
As far as I know, I will explain this below. You can google it and find lot of information too.
addShutdownHook() will register some actions which is to be performed on a Program's termination. The program that you start ends in two ways:
the main thread (Root) ends its running context;
the program meets some unexpected situation, so it cannot proceed further.
If you add a ShutdownHook, the hook will start a thread that will start running at time of termination only. For example:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Running Shutdown Hook");
}
});
will print a Running Shutdown Hook at the time of program termination at any point. You might even call a System.exit(0).
For examples, you can google, there are enough of them. And the question 'When should you use this' is like asking 'What does catch do in a try-catch statement'.
You might have many situations like:
your program had created many temporary files in filesystem you want to delete it;
you need to send a distress signal to another process/machine before terminating;
execute any clean-up actions, logging or after-error actions on unexpected behaviours.
All this will be needed for some point of time.
For examples you can go in here Example 1 or Example 2
You only worry about shutdown hooks when you want something to happen when a shutdown occurs on the virtual machine.
From Javadoc:
The Java virtual machine shuts down in response to two kinds of
events:
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or
system shutdown.
Thus, a shutdown hook is a initialized and unstarted thread that gets executed when a JVM shutdown occurs.
Popular examples of shutdown hooks exists in application servers (such as JBoss AS). When you press Ctrl+C, the JVM calls all the Runtime shutdown hooks registered (such as JBoss shutdown hooks) before exiting.
One case is, If you any daemon threads which needs to be stopped before your jvm shutdown (or) any other backend threads (mostly daemon threads) need to be gracefully exited, you will write shutdown hook and execute it using above code. Here is interesting discussion we had on SO couple of days ago. Shutdown hook
I learned that the stop method of the Application class of the
JavaFX application is called when it is about to terminate.
Does it mean that all the threads of my application continues to execute until the stop method has not returned?
So the termination of my application’s threads start meanwhile the execution of the stop method, or the termination of the threads start only after the stop method finished execution?
From docs here.
This method is called on the JavaFX Application Thread.
So if you have other threads performing their own tasks. Its your responsibility to handle them.
When you call close() on your primaryStage JavaFX calls the handler assigned to setOnCloseRequest() if you have override it before it will execute your code then closes the main Thread
If you have any other threads that are still running you have to close it yourself unless they are daemon threads as they close with the app anyway or call System.exit(0) your app will force close all the threads opened by your app
If you want I can provide an example that demonstrate my words
I have a Swing interface, when I click on a button a thread is created at infinity (the genus while(true)...).
My question is: when I close the main process, will the created threads be closed automatically?
Depends on if the threads you've started are daemon threads or not, and how you close the main process.
Here's the relevant documentation from the standard library:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
So, if you shut down the main process by System.exit or by using jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) then all threads will die when you shut down.
If you simply let the main thread (the thread running public static void main) drop off the edge of the main method, then the threads will continue to run.
Yes, as long as it's not set up as a daemon thread. You can view instrumented JVM's using the jps tool:
jps -l
It seems that daemon threads are always better - because they will be stopped by the VM after application main thread exits. Are there any other reasons to use non-daemon threads besides the cases when it is not possible to interrupt some operation ?
Thanks.
When you are writing a server (e.g. a servlet container), all your main has to do is to bootstrap and start HTTP listener threads, accepting threads, file system scanning threads, RMI threads, etc.
After bootstrap is done, main is no longer needed as everything happens asynchronously. In this case all essential threads are non-daemon as they have to live past the main method.
Even in Swing (desktop programming) the only requirement on main is to initialize the main window (JFrame). The rest happens in Swing listener threads (EDT) and various background threads.
In fact, any thread that should finish naturally (leaving its "run" method) should not be a daemon thread, as you don't want the JVM to terminate while they are doing their job.
This applies to every thread that you launch, and that you expect to terminate naturally.
As a rule of thumb, daemon threads are the exception, not the rule.
The one major difference is in how daemon threads exit; the JVM just stops them.
finally blocks are not executed
stacks are not unwound
You do not want to use daemon threads for things that need to be left in a known state such as file i/o, database transactions, etc.
You use non-daemon thread whenever you are doing something which you don't want to stop because an another thread exits. If the only purpose of a thread is to support other threads, then it makes sense to use a daemon thread.
If you want to exit when the main thread exits you can call System.exit(). Many applications don't keep their main thread and all the work is in threads it starts.
The VM may stop daemon threads in the middle of their executions, and persistent data could be corrupted because of that.
If you need more control of when a thread is safe to die, do not make it a daemon.
is there a way to determing if a jvm is shutting down normally? Shutdown hook can only spawn a thread, is there a way to determine if the JVM is existing normally or abnormally at that time?
You could write a file on startup and delete it again on graceful exit. If the JVM is gone but the file is still there you know that it crashed or has otherwise exited in a unintended manner.
I remembered a similar question being asked time ago. One possible course of action is the use of SignalHandler.
You can read the full article here. It appears to be related to IBM JVM but I think it is equally valid for Java Hotspot.
A little-known feature of Java is the
ability of an application to install
its own signal handler, which is
supported through the sun.misc.Signal
class. However, use caution when using
classes from the sun.misc package
because it contains undocumented
support classes that may change
between releases of Java. You can
install a Java handler for any signal
that is not used by the JVM. These
signal handlers are similar to native
handlers because they're invoked when
a native system signal is raised, but
they will always run as a separate
Java thread. Essentially, when a
signal is raised for which a Java
signal handler is available, the JVM's
"signal dispatcher thread" is woken up
and informed of the signal. The signal
dispatcher thread then invokes a Java
method to create and start a new
thread for the installed Java signal
handler. To write a Java signal
handler, define a class that
implements the sun.misc.SignalHandler
interface and register the handler by
using the sun.misc.Signal.handle()
method.
Check return sttaus using command $?
When the JVM is shutting down normally, this means that the main thread has ended. If the JVM is shutting down for some other resaon (e.g. the user pressed Strg+C), the main thread is still running. So you can store a reference to the main thread in your shutdown hook and check whether this thread is still alive. Of course this assumes that the main thread will normally be the last running thread in your application. I don't know how the situation is if one of the threads called System.exit(), but you could easily find this out.