Search code examples
javamultithreadingconcurrencyluaj

Terminate unresponsive thread


I have built a java application and have a thread thats doing something in the background when a button was pressed. The problem is, that thread might lock up, perhaps due to an infinite loop. Is there a way I can force terminate that thread?

EDIT: I am using LuaJ on the java platform. It has the potential of locking up and I don't really have much control over it apart from running it in another thread and killing it when either java or the script is finished.


Solution

  • No, there is not. Your only choice without major witchcraft is to call interrupt() on it and wait for it to hit a blocking call. At that point, it will throw an InterruptedException which you should have terminate the thread.

    If it is in a loop such as while(1); you can't really do much; you need to fix your thread to not do this, or to at least check a flag and stop itself.

    For example, you could rewrite:

    while(1) {
        doWork();
    }
    

    as:

    class Whatever {
        private volatile boolean stop = false;
        ...
            while (!stop) {
                doALittleWork();
            }
        ...
    }
    

    There used to be a Thread.stop() method that does this but it is deprecated for very, very good reasons and should not be used.

    EDIT: Since you're running presumably an interpreter, what you need to do is hook after every statement is executed (or so) and check your magic stop variable, and if so terminate Lua execution. Alternately, the Lua runtime may have its own "terminate" flag that you can use - I looked for documentation but their site is awful, so you may have to look at the code for this.

    Beyond that, you may have to patch the Lua4j source manually to add this feature. Your options are pretty limited and ultimately the Thread has to somehow control its own fate.