Java: set timeout on a certain block of code?

前端 未结 11 994
终归单人心
终归单人心 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:15

    Here's the simplest way that I know of to do this:

    final Runnable stuffToDo = new Thread() {
      @Override 
      public void run() { 
        /* Do stuff here. */ 
      }
    };
    
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future future = executor.submit(stuffToDo);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    
    try { 
      future.get(5, TimeUnit.MINUTES); 
    }
    catch (InterruptedException ie) { 
      /* Handle the interruption. Or ignore it. */ 
    }
    catch (ExecutionException ee) { 
      /* Handle the error. Or ignore it. */ 
    }
    catch (TimeoutException te) { 
      /* Handle the timeout. Or ignore it. */ 
    }
    if (!executor.isTerminated())
        executor.shutdownNow(); // If you want to stop the code that hasn't finished.
    

    Alternatively, you can create a TimeLimitedCodeBlock class to wrap this functionality, and then you can use it wherever you need it as follows:

    new TimeLimitedCodeBlock(5, TimeUnit.MINUTES) { @Override public void codeBlock() {
        // Do stuff here.
    }}.run();
    

提交回复
热议问题