Java: set timeout on a certain block of code?

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

    I can suggest two options.

    1. Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.

      void method() {
          long endTimeMillis = System.currentTimeMillis() + 10000;
          while (true) {
              // method logic
              if (System.currentTimeMillis() > endTimeMillis) {
                  // do some clean-up
                  return;
              }
          }
      }
      
    2. Run the method in a thread, and have the caller count to 10 seconds.

      Thread thread = new Thread(new Runnable() {
              @Override
              public void run() {
                  method();
              }
      });
      thread.start();
      long endTimeMillis = System.currentTimeMillis() + 10000;
      while (thread.isAlive()) {
          if (System.currentTimeMillis() > endTimeMillis) {
              // set an error flag
              break;
          }
          try {
              Thread.sleep(500);
          }
          catch (InterruptedException t) {}
      }
      

    The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.

提交回复
热议问题