I have a program \'foo\' running different threads, fooT1, fooT2, .. fooTn.
Now if I want write another program \'bar\', which could kill the thread fooTr, is that p
Actually the java debugger will allow you to kill a thread by injecting an exception into it. I was just trying to work out how to use this feature to kill a thread without wiping out the whole jvm, when I came across this question. If you run the jvm with command line options like:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8888 your.app.Main
and connect the debugger with something like:
jdb -attach 127.0.0.1:8888
you can type:
threads
to get a list of the running threads, and use the kill command to kill a running thread. The bit I'm currently not sure about is the syntax of this kill command, I have tried the obvious:
kill 0xe2e new java.lang.IllegalArgumentException("er");
and I get the messages:
killing thread: Swank REPL Thread
Thread not suspended
Expression must evaluate to an object
("Swank REPL Thread" is the thread I want to kill, and yes, I've tried suspending it first ;)
Still my inability to use the java debugger aside, it looks to me like a thread can be killed at random. Maybe you can just make sure you ignore all exceptions and keep running and that will be enough, but I'm not sure about that.
To my knowledge it is not possible to do this directly. What you could consider however is to create some kind of service on your 'foo' that can be called from 'bar' to kill the thread. There are, of course, hundreds of ways to implement this. My first thought would be to do this using RMI.
Until now isn´t possible to run to diferent programs in the same JVM, but some people is investigating it, in order to reduce the startup time and the memory and cpu usage of diferent java programs runing in the same machine
You could do this even without a separate application. Write your own startup class, which performs a pass-through of parameters to the original startup class of the application. Your class's main method though would create a thread that periodically checks the list of all threads (e.g., Thread.getAllStackTraces
or Thread.enumerate
), finds the offending thread, and invokes stop()
on it. Although Thread.stop
is deprecated, it still works.
Another option is to run the application under a Java debugger, say, jdb
and then suspend/kill the required thread. You could also add parameters to the application's startup so that the JVM can be attached to, then attach jdb
to the running JVM and suspect/kill the thread.