1

I have a scenario in which I am running unreliable code in java (the scenario is not unlike this). I am providing the framework classes, and the intent is for the third party to overwrite a base class method called doWork(). However, if the client doWork() enters a funked state (such as an infinite loop), I need to be able to terminate the worker.

Most of the solutions (I've found this example and this example) revolve around a loop check for a volatile boolean:

while (keepRunning) {
    //some code
}

or checking the interrupted status:

while (isInterrupted()) {
    //some code
}

However, neither of these solutions deal with the the following in the '//some code' section:

for (int i = 0; i < 10; i++) {
    i = i - 1;
}

I understand the reasons thread.stop() was depreciated, and obviously, running faulty code isn't desirable, though my situation forces me to run code I can't verify myself. But I find it hard to believe Java doesn't have some mechanism for handling threads which get into an unacceptable state. So, I have two questions:

  1. Is it possible to launch a Thread or Runnable in Java which can be reliably killed? Or does Java require cooperative multithreading to the point where a thread can effectively hose the system?

  2. If not, what steps can be taken to pass live objects such that the code can be run in a Process instead (such as passing active network connections) where I can actually kill it.?

  • possible duplicate of [How to kill a thread immediately from another thread in java?](http://stackoverflow.com/questions/4530744/how-to-kill-a-thread-immediately-from-another-thread-in-java) – Buddy May 13 '15 at 21:58
  • At best, that says the answer to my first question is no. If that's the case, I'd like to know what alternatives exist (such as running in a Process) – user4896445 May 13 '15 at 22:15
  • Can you provide an example of "threads which get into an unacceptable state"? – m0skit0 May 13 '15 at 22:56
  • Yes - one which is locked in a loop where it isn't checking a boolean. See the poorly coded for loop in the question. – user4896445 May 14 '15 at 01:38

1 Answers1

0

If you really don't want to (or probably cannot due to requirement of passing network connections) spawn new processes, you can try to instrument code of this 'plugin' when you load it's class. I mean change it's bytecode so it will include static calls to some utility method (eg ClientMentalHealthChecker.isInterrupted()). It's actually not that hard to do. Here you can find some tools that might help: https://java-source.net/open-source/bytecode-libraries. It won't be bullet proof because there are other ways of blocking execution. Also keep in mind that clients code can catch InterruptedExceptions.

sasol
  • 1