Sometimes the system process of a java application doesn't fully shutdown. This is mainly because one or more threads didn't die.
One can call:
System.exit(0);
But this kills all threads.
I want all my threads to shutdown correctly so i don't plan on using System.exit. But sometimes due to circumstances one or more threads don't die correctly. This causes the application to not fully shutdown and linger in the background sometimes even locking up resources.
My first thought was writing an ExitWatcher which starts when program stops and calls system.exit after 10 seconds if the program is still alive. I quickly found out that the ExitWatcher now prevents the program from shutting down ;-)
How do you give a java program time to shutdown correctly (ie close all threads correctly) but at the same time have a backup plan that calls System.exit if shutdown takes too long?
You can use daemon threads when you don't want a thread to prevent a program from exiting (so using setDaemon(true) on your ExitWatcher thread would solve your immediate problem). However I doubt you really need or want an ExitWatcher, as situations like that are usually relatively easily prevented with proper design.
Proper shutdown procedures include interrupting threads that are active (and designing them so they behave nicely when interrupted), using daemon threads where necessary, shutting down connections properly etc. Using a mechanism like your ExitWatcher is more of a hackish approach, as it indicates your program doesn't always behave nicely at shutdown.
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
If a Java process hangs (due to bug in JNI (faces deadlock), Can it result in blocking of entire JVM? i.e. all processes and threads getting blocked?
due to bug in JNI Yes. If you call into native code a bug can easily bring down the entire JVM (or block everything).
No. The thread or threads in deadlock will remain blocked, but other threads can run independently in other programs or even in the same program. Obviously deadlocks should be avoided whenever possible, but the affected threads will only be the threads in deadlock and any and all threads waiting on the completion of those threads.
Normally every application has it's own JVM instance running. So you could not crash other applications by trying to crash your current JVM . However some application share one JVM like a Web server for instance.
Another scenario would be if it crashes anything on an operating system level. Well then everything related to that will shut down.
I like the fact that threads can share some resources but they need to release their private resources in the end. Meantime, some computations may be obsolete and you kill them, using Task Manager. I am looking for the same thing done in one JVM process.
You say that thread.stop is unreliable and propose that my thread polls the interrupted flag instead. But, polling is not efficient, right? You do not want neither performance penalty nor polluting your code with ubiquitous if (interrupted) blocks. What is going to be the best appropriate option here?
Killing one process in an application that is composed of several interacting processes can be dangerous, but it is not usually as dangerous as killing a thread.
The ways in which one process depends on the state of another often are more limited. If the processes only interact through network communication, it probably won't be hard to design an application that can gracefully recover from having one of its processes killed. Likewise, if the processes interact through a shared transactional database.
It gets harder to handle a KILL safely if the processes interact through shared files. And it gets pretty close to impossible to guarantee the safety of an arbitrary KILL if the processes interact via shared memory.
Threads always interact via shared memory. A KILL that can't be handled, could come at any time. There's just no way to guarantee that killing some thread won't leave the whole program in a corrupt state.
That's why t.stop() is deprecated in Java. The real question should be, "why did they ever implement t.stop() in the first place?"
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.
I have J2SE application running in 1.5 java VM in RHEL OS. One of the task of the application is to create 3 infinitely running user threads, during startup. The purpose is to check for a request of a particular type in backend DB table and do corresponding operations.
As we observed, the long running threads suddenly stops running, but still the application is alive and JVM process can be seen, in ps -ef|grep java
Can someone throw light on why threads which are created to run in infinite loop, stops suddenly? Any ideas on how to detect this issue and possible resolution will be of great help
With Regards,
Krishna
I would suggest sending a Ctrl+Break to your app, dumping the threads and analysing the output. Perhaps your threads are waiting for some input (IO). Perhaps they're deadlocked. Perhaps they've exited with an uncaught exception. The thread dump will tell you what's going on (and it helps if you name your threads in advance so you can identify them in the dump).
Perhaps you are having unhandled exceptions.
First of all, you should log all your thread activity (you can use log4j to achieve this).
You can also override the uncaughtException method of the ThreadGroup class and create alerts for when a thread dies due to an exception that has not been caught.