title: Skip function if it takes too long
body: <p>In Java I have a function that processes a text file in a certain way. However, if it takes too much time the process will most likely be useless (whatever the reason is) for that text file and I would like to skip it. Furthermore, if the process takes too long, it also uses too much memory. I've tried to solve it this way, but it doesn't work:</p>
  
  <pre><code>for (int i = 0; i&lt;docs.size(); i++){
      try{
          docs.get(i).getAnaphora();
          }
      catch (Exception e){
          System.err.println(e);
      }
   }
  </code></pre>
  
  <p>where <code>docs</code> is just a <code>List</code> of files in a directory. Usually I have to manually stop the code because it is 'stuck' at a particular file (depending on the contents of that file). </p>
  
  <p>Is there a way of measuring time for that function call and tell Java to skip the file the function takes more than, let's say, 10 seconds?</p>
  
  <p><em>EDIT</em><br />
  After scraping a few different answers together I came up with this solution which works fine. Perhaps someone else can use the idea as well.</p>
  
  <p>First create a class that implements Runable (this way you can pass in arguments to the Thread if needed):</p>
  
  <pre><code>public class CustomRunnable implements Runnable {
  
      Object argument;
  
      public CustomRunnable (Object argument){
          this.argument = argument;
  }
  
      @Override
      public void run() {
          argument.doFunction();
      }
  }
  </code></pre>
  
  <p>Then use this code in the <code>main</code> class to monitor the time of a function (<code>argument.doFunction()</code>) and exit if it takes to long:</p>
  
  <pre><code>Thread thread;
  for (int i = 0; i&lt;someObjectList.size(); i++){          
      thread = new Thread(new CustomRunnable(someObjectList.get(i)));
      thread.start();
      long endTimeMillis = System.currentTimeMillis() + 20000;
      while (thread.isAlive()) {
          if (System.currentTimeMillis() &gt; endTimeMillis) {
          thread.stop();
          break;
      }
      try {
          System.out.println("\ttimer:"+(int)(endTimeMillis - System.currentTimeMillis())/1000+"s");
          thread.sleep(2000);
          }
      catch (InterruptedException t) {}
      }
  }
  </code></pre>
  
  <p>I realise <code>stop()</code> is depcecated, but I haven't found any other way to stop and exit the thread when I want it to stop.</p>