简体   繁体   中英

How to stop a 3rd party method, in java?

Let's say I have this code running in its own thread:

SomeObject someObject = new SomeObject();
someObject.doLongTask();

That doLongTask() method can take a long time to finish. I also do not have the ability to modify its source. But I want to be able to terminate whatever it's doing, without killing the rest of my application. How can I terminate that method while it's running?

First, I think you should read this article: Why is Thread.stop() Deprecated?

Because allowing threads to be killed at will by other threads can introduce many deadlock problems in multi-threaded code that are not easy to think about and mitigate ahead of time, the Java developers decided to not support this feature. However, there are ways you can get around this problem. Take a look at the code below, with the understanding that this may not actually be a full solution to your problem, depending on how doLongTask() is implemented:

long timeout = ...//some number of milliseconds to wait
final SomeObject someObject = new SomeObject();
Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
        someObject.doLongTask();
    }
});
t.join(timeout);
if(t.isAlive()){
    t.interrupt();
    //handle failed task here;
}

This code assumes that SomeObject.doLongTask() is designed to look for thread interrupts periodically and terminate early if one is detected. Otherwise, t will continue to run doLongTask() until it completes. If doLongTask() isn't coded to handle thread interrupts and you don't have access to source code, you may be out of luck, short of running that long task in a separate process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM