Executor Service - timeout of thread

后端 未结 3 1128
Happy的楠姐
Happy的楠姐 2021-02-04 19:56

While I was exploring ExecutorService, I encountered a method Future.get() which accepts the timeout.

The Java doc of this method

3条回答
  •  醉酒成梦
    2021-02-04 20:27

    my callable will interrupt after the specified time(timeout) has passed

    Not true. The task will continue to execute, instead you will have a null string after the timeout.

    If you want to cancel it:

      timeout.cancel(true) //Timeout timeout = new Timeout();
    

    P.S. As you have it right now this interrupt will have no effect what so ever. You are not checking it in any way.

    For example this code takes into account interrupts:

        private static final class MyCallable implements Callable{
    
        @Override
        public String call() throws Exception {
            StringBuilder builder = new StringBuilder();
            try{
                for(int i=0;i

    And then:

            ExecutorService service = Executors.newFixedThreadPool(1);
        MyCallable myCallable = new MyCallable();
        Future futureResult = service.submit(myCallable);
        String result = null;
        try{
            result = futureResult.get(1000, TimeUnit.MILLISECONDS);
        }catch(TimeoutException e){
            System.out.println("No response after one second");
            futureResult.cancel(true);
        }
        service.shutdown();
    

提交回复
热议问题