modeller
modeller

Reputation: 3850

Java how to timeout a thread WITHOUT using future.get and without blocking parent thread

I am looking for ways to time out a thread execution and found below example: https://stackoverflow.com/a/16231834/10015830

Future<?> future = service.submit(new MyCallable());
try {
    future.get(100, TimeUnit.MILLISECONDS);
} catch (Exception e){
    e.printStackTrace();
    future.cancel(true); //this method will stop the running underlying task
}

But my need is different from above example: I do not want the parent thread to be blocked at future.get. In other words, I do not need to get the result of my callable. Because in my actual application, the parent thread is executed periodically (a scheduled task, say, 5 sec periodically).

Is there a way timeout a thread WITHOUT using future.get and without blocking parent thread? (It seems invokeAll is also blocking).

Upvotes: 0

Views: 717

Answers (1)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

You can cancel long running task from a timer task:

import java.util.Timer;
import java.util.TimerTask;

Timer timer = new Timer();

    Future<?> future = service.submit(new MyCallable());
    TimerTask controlTask = new TimerTask(){
        @Override
        public void run() {
            if (!future.isDone()) {
                future.cancel(true);
            }
        }       
    };
    long delay = 100;
    timer.schedule(task, delay);

Upvotes: 1

Related Questions