determine if an application is shutting down normally - java

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.

Related

How to identify OS interrupts in java code and perform some action? [duplicate]

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

How to kill a java thread using VisualVM or using a unix command?

I m using windows 7 OS. I have around 6 threads in my application. For the purpose of testing the alerts to check the health of the threads, i need to kill the threads manually and check if the alerts are working properly. Can we kill a thread like how we kill a process with its pid?
Dan Woods documented how to kill a thread in this blog entry...
https://web.archive.org/web/20160302023213/http://www.rhcedan.com/2010/06/22/killing-a-java-thread
The steps he performed involved using a debugger (JDB) and injecting an exception in the thread's execution. Specifically...
Ensure that your java program is started with the following parameters:
-Dcom.sun.management.jmxremote.port=50199
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Xrunjdwp:transport=dt_socket,address=50100,server=y,suspend=n
This will allow us to attach the java debugger to the running process, after
we identify which Thread is causing the problem. Also, make sure that
you have your iptables setup appropriately so as to only allow
connections on 50100 and 50199 from the hosts/workstations that you manage.
Identify the offending thread:
Kill the thread. In this example, the ThreadName is “btpool0-0?. Fire up the java debugger (also shipped with the JDK distribution), and attach to the running JVM…
[root#host ~]# jdb -attach 50100
Get a list of the running threads — this will also give us the thread id as the JVM sees it:
> threads
--snip--
(org.mortbay.thread.BoundedThreadPool$PoolThread)0x25cb
btpool0-0 running
--snip--
The thread id that we’re going to kill is “0x25cb”. The first step of killing the thread is to jump into it, and suspend it…
thread 0x25cb
btpool0-0[1] suspend 0x25cb
btpool0-0[1] step
Step completed: <... snip ...>
btpool0-0[1] kill 0x25cb new java.lang.Exception()
killing thread: btpool0-0
btpool0-0[1] instance of
com.site.package.name(name='btpool0-0', id=9675) killed btpool0-0[1]
Exit the java debugger, and you’re done!
There is no safe way to "kill" a thread without killing the process it is in. It not something you would do deliberately. For testing purposes I would add code to your application to support this.
It's not true. You can always attach to the JVM process with GDB and do a call pthread_kill if you know the thread id. You only need to translate from the java thread dump (do a kill -3) which gives you a hex id, (native id), then look into the list of threads in GDB (info threads) and locate the real thread id.
This is proven to work.
As Peter says, you can't do this safely. Indeed on some platforms Thread.kill is not even implemented. However:
If this is just for testing, a unit test that called Thread.kill would be reasonable ... assuming it worked on the test platforms where it needed to work. (A "loud" comment in the source code would be in order to help people porting the unit test ...)
Another alternative is to add some code to the thread runnable that allows your unit tests to tell it to die. If the thread code needs to be (almost) production code for this to work, you could create a subclass that overrides something so that it "breaks" in a way that suits your purposes ... for testing. In fact, this approach allows you to cause the threads "break" in controlled ways, potentially allowing you to test different aspects of your alerting code.
You can't do it from outside (OS or debugger), you'll have to write your own Thread watchdog that can interact with the user and kill the thread you want.
Try to look here for how to handle signals with java
In java you can not kill the like unix . Either you can interrupt the tread in java or you can kill the process in unix .
Wait for some time in the thread and kill the thread in the code - simple way.
As mentioned in a previous post by buzz3791, it works by using jdb. However the change that I noticed is, you can't kill the thread, but you can interrupt or suspend the thread.
#jdb -attach 50100
threads --This will show all threads running on the jvm under Groups and Reference Handler section.
Groups
Reference Handler
:(com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary)0x36c1:
OrientDB (/xxx.xxx.xxx.xxx:123) <- BinaryClient (/xxx.xxx.xxx.xxx:678)
thread 0x36c1-- This will be the thread id that can be picked from one of the threads in the thread that you wish to kill/interrupt and run this interrupt 0x36c1
OrientDB (/xxx.xxx.xxx.xxx:123) <- BinaryClient (/xxx.xxx.xxx.xxx:678)[1] interrupt 0x36c1
you can try multiple times the same interrupt command and if it is already interrupted, it will show that the thread id is invalid. Thus you know that the thread is killed, this can be verified by looking at the stack trace and confirmed.
Tested this on the OrientDB database server with jdk 8 and it works.

How to generate Thread dumps when JVM terminates automatically

Problem scenario : The problem is noticed in sonic MF container (The jvm).The container has hosted some java services responsible for db operations and message transformations.Once started, the container runs fine for 2-3 weeks and terminates by its own without throwing any exceptions.
After much research, we are unable to find out why or what has triggered the jvm (MF Container) to shutdown.
Is there a way by which I can get the thread dumps when the jvm goes down automatically ? I'm using java 1.6. Is there any other approach to this problem I should follow ?
Thanks in advance.
You could try java.lang.Runtime.addShutdownHook(), and have the hook iterate over all threads and dump their stack traces with Thread.getAllStackTraces(). However, if the JVM was shutdown by Runtime.halt() then the hooks won't be called. More complicated would be to use instrumentation to hook into the calls to Runtime.exit() and Runtime.halt() (or Shutdown.sequence(), see edit #2), so you can see exactly what's happening at the time that either is called.
EDIT: Another way of doing it would be to install a SecurityManager which doesn't enforce any security, but which dumps the list of threads whenever SecurityManager.checkExit() is invoked, since both halt() and exit() call that security manager method. This would be a lot easier than using instrumentation, and you could even decide to throw an exception in addition to logging what the threads are doing.
EDIT 2: The system the JVM is running on can tell the JVM to terminate, in which case using a security manager won't work. Nor will using instrumentation on Runtime.exit() or Runtime.halt(), since the method that gets invoked is java.lang.Shutdown.exit(). And if the JVM is shutting down because the last daemon thread finished then Shutdown.shutdown() is invoked. But shutdown hooks will work in either of those situations. So you should always use the shutdown hooks, even if you're also going to use the security manager or instrumentation.
See also https://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-VM/html/hangloop.html "Troubleshooting Hanging or Looping Processes"
However, at least in my case, Eclipse is hung, and does not respond to any of these.

What are those java threads starting with "pool"?

I have a problem with a Tomcat server that is unable to shutdown gracefully. I have taken a thread dump after I issued the shutdown command, and it looks like this:
http://pastebin.com/7SW4wZN9
The thread which I believe is the "suspect" that does not allow the VM to shut down is the one named "pool-4-thread-1". The rest of them are either daemon threads or internal VM threads. While trying to find out what this thread is for, I noticed that there are other java programs out there that create threads with similar names (For example, JVisualVM creates such threads).
So I'm wondering if someone else knows what this thread is and how it can be created.
These threads are probably created by an ExecutorService that you created in your code somewhere (directly or indirectly through a library) and that needs to be shutdown (for example in a ServletContextListener).

Do I Have to JNI Detach an Attached Thread?

I have some native thread that needs to call into Java. For that, I need to attach the thread to the VM using AttachCurrentThread. Since this callback will happen quite often, the thread should probably stay attached. Calling AttachCurrentThread multiple times is fine ("Trying to attach a thread that is already attached is a no-op.")
Do I have to call DetachCurrentThread before the thread exits, will it happen automatically, or is it not even required? What happens if I must call detach, but don't? Would it just "leak," or could this even corrupt the VM state?
I have checked the Java Native Interface specification, but either missed this, or it really is unspecified.
My question applies specifically to Sun JDK 6 on Windows XP.
I think that the confirmation that you want is here: http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#wp1060
A native thread attached to the VM must call DetachCurrentThread() to detach itself before exiting.
And in the next section, there's the rationale:
The VM waits until the current thread is the only non-daemon user thread before it actually unloads. User threads include both Java threads and attached native threads.

Categories