How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?

后端 未结 7 1761
陌清茗
陌清茗 2020-11-30 08:55

I have a method that I would like to call. However, I\'m looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.

I\'m

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 09:44

    You should take a look at these classes : FutureTask, Callable, Executors

    Here is an example :

    public class TimeoutExample {
        public static Object myMethod() {
            // does your thing and taking a long time to execute
            return someResult;
        }
    
        public static void main(final String[] args) {
            Callable callable = new Callable() {
                public Object call() throws Exception {
                    return myMethod();
                }
            };
            ExecutorService executorService = Executors.newCachedThreadPool();
    
            Future task = executorService.submit(callable);
            try {
                // ok, wait for 30 seconds max
                Object result = task.get(30, TimeUnit.SECONDS);
                System.out.println("Finished with result: " + result);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (TimeoutException e) {
                System.out.println("timeout...");
            } catch (InterruptedException e) {
                System.out.println("interrupted");
            }
        }
    }
    
        

    提交回复
    热议问题