Java: set timeout on a certain block of code?

前端 未结 11 1002
终归单人心
终归单人心 2020-11-27 03:45

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

11条回答
  •  一生所求
    2020-11-27 04:19

    If it is test code you want to time, then you can use the time attribute:

    @Test(timeout = 1000)  
    public void shouldTakeASecondOrLess()
    {
    }
    

    If it is production code, there is no simple mechanism, and which solution you use depends upon whether you can alter the code to be timed or not.

    If you can change the code being timed, then a simple approach is is to have your timed code remember it's start time, and periodically the current time against this. E.g.

    long startTime = System.currentTimeMillis();
    // .. do stuff ..
    long elapsed = System.currentTimeMillis()-startTime;
    if (elapsed>timeout)
       throw new RuntimeException("tiomeout");
    

    If the code itself cannot check for timeout, you can execute the code on another thread, and wait for completion, or timeout.

        Callable run = new Callable()
        {
            @Override
            public ResultType call() throws Exception
            {
                // your code to be timed
            }
        };
    
        RunnableFuture future = new FutureTask(run);
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(future);
        ResultType result = null;
        try
        {
            result = future.get(1, TimeUnit.SECONDS);    // wait 1 second
        }
        catch (TimeoutException ex)
        {
            // timed out. Try to stop the code if possible.
            future.cancel(true);
        }
        service.shutdown();
    }
    

提交回复
热议问题