ssedano ssedano - 1 year ago 132
Java Question

How to kill a Thread in Java that is in state RUNNING?

It is possible to kill a thread that is in state

in a non programatically way?

I know that
command in
can show threads. Can I kill the thread in the OS?

I'd like to know if there is a way to link a thread to a process so I can kill only that specific thread and not the application.

We had a bug in our code that kept a thread in state
in a synchronized method. The thread kept the
on the object "hanging" the application.

The bug is fixed. But I wonder if is possible.

Answer Source

The short answer is "maybe, but you should not and most of the time it won't work either".

The long answer is:

"Maybe..." Some JVM implementation map java threads to OS threads and some do not. If the JVM does a mapping to a native OS thread, you might be able to kill that thread with some process tool that the OS provides (like kill on *nix). If the JVM does green threads, meaning it doesn't map a Java thread to an OS level thread, then you are basically out of luck using OS level tools. Luckily only very few JVM implementations do this. An approach that can be used regardless in which way the JVM organizes it's threads, is using the java debugger. This article describes the procedure of doing it:

"but you should not do it" Killing a thread on the OS level will almost certainly leave the JVM in an undefined state (read "jvm might crash or delete all files on your disk or do whatever it fricking pleases to do"). Even when going the debugger way, only a very small amount of java applications (read "no application made on this planet") will properly handle the event that an outside application is killing one of it's threads. As a result these applications will be put in an undefined state (read "application might crash or delete all files on your disk or do whatever it fricking pleases to do").

"and most of the time it won't work either" If the thread is really stuck with some blocked IO etc, then killing the thread won't work, it will just not respond. If a program is stuck it's probably better to kill the whole program, find the issue with the program and fix it instead of killing a single thread.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download