Time out method in java

后端 未结 4 1671
无人共我
无人共我 2020-12-06 13:41

In a java class I have a method that sometimes takes a long time for execution. Maybe it hangs in that method flow. What I want is if the method doesn\'t complete in specifi

4条回答
  •  失恋的感觉
    2020-12-06 14:34

    Based on the above snipplet, I tried creating a glorified spring bean.

    Such executor runs the passed limitedRuntimeTask in limited runtimeInMs. If the task finishes within its time limits, the caller continues normally in execution.

    If the limitedRuntimeTask fails to finish in the defined runtimeInMs, the caller will receive the thread execution back. If a timeBreachedTask was defined, it will be executed before returning to caller.

    public class LimitedRuntimeExecutorImpl {
    
    
    public void runTaskInLessThanGivenMs(int runtimeInMs, final Callable limitedRuntimeTask, final Callable timeBreachedTask) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    LOGGER.info("Started limitedRuntimeTask");
                    limitedRuntimeTask.call();
                    LOGGER.info("Finished limitedRuntimeTask in time");
                } catch (Exception e) {
                    LOGGER.error("LimitedRuntimeTask exception", e);
                }
            }
        });
        thread.start();
    
        long endTimeMillis = System.currentTimeMillis() + runtimeInMs;
    
        while (thread.isAlive()) {
            if (System.currentTimeMillis() > endTimeMillis) {
                LOGGER.warn("LmitedRuntimeTask did not finish in time (" + runtimeInMs + ")ms. It will run in vain.");
                if(timeBreachedTask != null ){
                    try {
                        LOGGER.info("Executing timeBreachedTask");
                        timeBreachedTask.call();
                        LOGGER.info("Finished timeBreachedTask");
                    } catch (Exception e) {
                        LOGGER.error("timeBreachedTask exception", e);
                    }
                }
                return;
            }
            try {
                Thread.sleep(10);
            }
            catch (InterruptedException t) {}
        }
    
    }
    

    }

提交回复
热议问题