Jakir00
Jakir00

Reputation: 2073

Terminate a Thread thats running a jar

I have a class that extends Thread and when started, it runs a jar's Main method. When I terminate the Thread it does not kill the process it started. How do I go about that? Thanks!

Below if the run() method from my custom Thread class.

@Override
    public void run() {
        if(parent != null) {
            MessageConsole console = new MessageConsole(parent.getConsole().getTextPane());
            console.redirectOut(new Color(240, 240, 240), null);
            console.redirectErr(Color.RED, null);
            console.setMessageLines(20);
        }
        if(oParent != null) {
            MessageConsole console = new MessageConsole(oParent.getConsole().getTextPane());
            console.redirectOut(new Color(240, 240, 240), null);
            console.redirectErr(Color.RED, null);
            console.setMessageLines(20);
        }
        try {
            somejar.SomeJar.main(args);
        } catch (Exception ex) {
            System.err.println("Engine failed to start!\nSuggestion: Restart the application, and if the issue is not fixed reinstall the application.");
        }
    }

Upvotes: 1

Views: 744

Answers (2)

Stephen C
Stephen C

Reputation: 718758

When I terminate the Thread it does not kill the process it started. How do I go about that?

There is no reliable way to do that.

Firstly, there is no reliable way to terminate the thread. The preferred way to try is to call Thread.interrupt() on the thread, but this may be ignored. If you call the deprecated method Thread.stop(), you are liable to destabilize your JVM.

Second, even assuming you kill the JAR thread, you cannot reliably kill any child threads that it created. You cannot reliably distinguish the child threads from other threads created by other parts of your application. And if you could identify them, you cannot reliably kill them.

The best you can do is launch a new JVM as an external process to run the JAR. Under normal circumstances a JVM can reliably kill an external process that it has created. (There are exceptions, e.g. setuid commands, but they shouldn't be an issue here.)

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533492

You cannot terminate a thread without terminating the process.

You can signal it to stop e.g. interrupt() or throw an exception, but the only way to get it to stop is for it to return or throw a Throwable from the run() method.

Upvotes: 0

Related Questions