Does a Future timeout kill the Thread execution

后端 未结 4 432
一个人的身影
一个人的身影 2020-12-23 08:55

When using an ExecutorService and Future objects (when submitting Runnable tasks), if I specify a timeout value to the future\'s get f

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 09:31

    It does not. Why would it? Unless you tell it to.

    There is a very valid concern here in case of a Callable for example. If you waited for the result for say 20 seconds and you did not get it, then you are not interested in the result anymore. At that time you should cancel the task at all.

    Something like this:

    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
        }
    

提交回复
热议问题