title: JAVA: How to stop the execution of a function after a specific time?
body: <p>I want to implement iterative deepening (incremental tree building). This is the part of my code I will ask about:</p>
  
  <pre><code>        ExecutorService executorService = Executors.newSingleThreadExecutor();
  
          Set&lt;Callable&lt;Integer&gt;&gt; callables = new HashSet&lt;Callable&lt;Integer&gt;&gt;();
  
          callables.add(new Callable&lt;Integer&gt;() {
              public Integer call() throws Exception {
                  iterativeDeepening(depthLimit, board);
                  return -1;
              }
          });
          callables.add(new Callable&lt;Integer&gt;() {
              public Integer call() throws Exception {
                  Thread.sleep(500);
                  return 1;
              }
          });
          try{
              executorService.invokeAny(callables, 1000, TimeUnit.MILLISECONDS);
          }catch(TimeoutException | InterruptedException ex){
              executorService.shutdown();
          }
  
          executorService.shutdown();
  </code></pre>
  
  <p>From what I read about invokeAny() with time limit it should end executing its Callable objects as soon as the deadline is reached. It works when I put long sleep instead of my function iterativeDeepening(depthLimit, board). How to make it work with my function? 
  Below I paste the code to this function:</p>
  
  <pre><code>    public void iterativeDeepening(byte depthLimit, byte[] board){
  
      for(byte depth=1;depth&lt;depthLimit;depth++){
          GameTree gameTree= new GameTree();
          byte[] tempBoard = new byte[14];
          for(byte i=0;i&lt;14;i++){
              tempBoard[i] = board[i];
          }
          Node &lt;byte[]&gt; root= new Node&lt;byte[]&gt;(tempBoard, player);
          try {
              gameTree.buildGameTree(depth, root);
          } catch (OutOfMemoryError E) {
              gameTree.eraseGameTree(depth,root);
              System.gc();
          }
  
          MiniMax minimax = new MiniMax(player);
          move= minimax.selectMove(depth, root);
  
      }
  }
  </code></pre>
  
  <p>If you know a better way to make it or know how to successfully stop execution of my function please let me know. I tried also a Runnable Interface mentioned in this topic:
  <a href="https://stackoverflow.com/questions/4252187/how-to-stop-execution-after-a-certain-time-in-java">How to stop execution after a certain time in Java?</a>
  but it just worked the same.</p>