Time limit on individual threads with ExecutorService

后端 未结 5 1069

I have an ExecutorService managing a number of Callables. The tasks that the Callables run are mostly black box transformations and number crunching. Under certain condition

5条回答
  •  囚心锁ツ
    2020-12-09 05:38

    Use a ScheduleExecutorService to schedule a task to taskFuture.cancel(true) the long running task when the timeout is reached. If the task finishes before then it won't be cancelled.

    ExecutorService service = Executors.newFixedThreadPool(N);
    ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();
    
    public  Future executeTask(Callable c, long timeoutMS){
       final Future future = service.submit(c);
       canceller.schedule(new Callable(){
           public Void call(){
              future.cancel(true);
              return null;
           }
        }, timeoutMS, TimeUnit.MILLI_SECONDS);
       return future;
    }
    

提交回复
热议问题