0

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).

modeller
  • 3,770
  • 3
  • 25
  • 49
  • 1
    What do you mean by _timeout a thread_? You just want to cancel a task after 100 ms if it hasn't completed? – Sotirios Delimanolis Apr 07 '19 at 16:12
  • @SotiriosDelimanolis To `cancel` a task, from where? The parent thread may have been terminated already. Is it possible to cancel from within the child thread automatically? – modeller Apr 07 '19 at 16:15

1 Answers1

1

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);
Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
  • Looks like a thread could not time/monitor/cancel itself. It has to use a separate thread as monitor, this monitoring thread can be a parent thread, or a third dedicated thread (in your example it is a timer task, which is a thread in its nature). – modeller Apr 07 '19 at 18:41