title: Setting a maximum execution time for a method/thread
body: <p>I have a method, which writes to the database. The requirement is to make sure that this method does not execute after a certain time elapses. If it returns before that, then nothing should be done.</p>
  
  <p>The one basic approach that I can think of is doing something like this.</p>
  
  <pre><code>public class LimitedRuntime {
  
      public static void writeToDb(){
              // writes to the database
      }
  
      public static void main(String[] args) {
          long totalExecutionTime = 8000L;
          long startTime = System.currentTimeMillis();
  
          while(System.currentTimeMillis() - startTime &lt; totalExecutionTime )
          {
              writeToDb();
          }   
      }
  }
  </code></pre>
  
  <p>One problem with this approach is that even if the method returns before the max total execution time, even then the program halts so as to wait for the time to elapse.</p>
  
  <p>How can I do this better (or maybe more correctly) ? And if we use <code>Thread</code>, how can we find out which <code>Thread</code> executes that method ?</p>