views:

40

answers:

1

I have a GUI which resembles an interpreter. It allows the user to write a script in Jython (implementation of Python in Java) and run it whenever he wants. Apart from that, I also wish to allow the user to instantly terminate the run whenever he wants.

Thing is, I don't really know how to do it. The script is being run on a different Thread, but I don't know of any secure way to stop/interrupt/terminate a thread in the middle of its run, let alone not knowing what is being run by the thread/script (it could be a simple task or maybe some sort of a heavy SQL query against a DB, and a DB is something which requires careful resource handling).

How can I instantly terminate such run on demand?

A: 

Unfortunately there is no safe way to terminate a thread instantly and safely. That is part of the reason why Thread.stop has been deprecated.

It is a complicated problem, and it really depends on how your thread works. A generic solution for all threads to do this does not exist. It sounds like your thread is not in a loop, so polling a variable on a loop will not do. But you may be able to a variation:

MyThread extends Thread {
    PythonProcess p;

    void run() {
        p = startPython();
    }

    void stopMe() {
        p.halt();
    }
}

As a last resort you can still use the deprecated Thread.stop, but it will be unsafe and should be avoided if at all possible. Other then that maybe you can do a process fork and handle it manually at the OS level, but that is not very java like.

Rontologist