Time limit on individual threads with ExecutorService

后端 未结 5 1131

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:40

    The best way for you to do this would be to introduce one more Executor. You can use a ScheduledExecutorService to cancel all long running tasks for example:

    ExecutorService service = Executors.newFixedThreadPool(N);
    
    ScheduledExecutorService canceller = Executors.newScheduledThreadPool(1);
    
    public void executeTask(Callable c){
       final Future future = service.submit(c);
       canceller.schedule(new Runnable(){
           public void run(){
              future.cancel(true);
           }
        }, SECONDS_UNTIL_TIMEOUT, TimeUnit.SECONDS);
    }
    

提交回复
热议问题