Executor Service - timeout of thread

后端 未结 3 1129
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<String>{
    
        @Override
        public String call() throws Exception {
            StringBuilder builder = new StringBuilder();
            try{
                for(int i=0;i<Integer.MAX_VALUE;++i){
                    builder.append("a");
                    Thread.sleep(100);
                }
            }catch(InterruptedException e){
                System.out.println("Thread was interrupted");
            }
            return builder.toString();
        }
    }
    

    And then:

            ExecutorService service = Executors.newFixedThreadPool(1);
        MyCallable myCallable = new MyCallable();
        Future<String> 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();
    
    0 讨论(0)
  • 2021-02-04 20:30

    The timeout on get() is for how long the 'client' will wait for the Future to complete. It does not have an impact on the future's execution.

    Object result;
    int seconds = 0;
    while ((result = fut.get.(1, TimeUnit.SECOND)) == null) {
        seconds++;
        System.out.println("Waited " + seconds + " seconds for future";
    }
    
    0 讨论(0)
  • 2021-02-04 20:33

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

    The above statement is wrong, Usually Future.get is blocking. Specifying the timeout allows you to use it in a non blocking manner.

    This is useful for instance in time critical applications, if you need a result within let's say 2 seconds and receiving after that means you can't do anything with that.

    0 讨论(0)
提交回复
热议问题