简体   繁体   中英

Kill a Java Thread without looping

I'm using an external lib (Generex) in my project, and one constructor may take a very long time to execute, so I'd like to have a timeout (let's say 50 ms), and be able to know if the timeout has been reached or not.

So I was thinking at using a dedicated thread, and wrote the following code:

@Test
public void isComputable() throws InterruptedException {
    for (int i=0; i<10;i++)
        System.out.println(check());

    Thread.sleep(300000);
}

private static boolean check() {

    final Thread stuffToDo = new Thread(() -> {while(true){}});

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future future = executor.submit(stuffToDo);
    executor.shutdown();

    try {
        future.get(50, TimeUnit.MILLISECONDS);
    }
    catch (InterruptedException | ExecutionException | TimeoutException ie) {
        stuffToDo.interrupt();
        stuffToDo.stop();
        return false;
    }
    if (!executor.isTerminated())
        executor.shutdownNow();
    return true;
}

I replaced the call to the external lib with a while(true) loop, yet it is important to note that, in my case, I cannot use a loop to check if the thread was interrupted.

When executing this code, I've got well the answer after 50 ms for each call, yet the thread is not destroyed, and there is a high CPU usage, as we can see with JProfiler (note that the loop in the test over i is just to have a nicer chart):

在此处输入图片说明

Does anyone have any idea on how to solve this issue please?

Note: I know that I should not use the deprecated stop method, I just tried everything I know to kill the thread.

You either have to check for an interrupt regularly in your code callex or you have to run the code in another process. These are the only ways you can either interrupt or kill the process running the code.

I suggest taking a stack trace of the long running thread to help fix it in the future.

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