title: How to limit a thread's execution time and terminate it if it runs too long?
body: <p>A general case for my question was, how do we detect if a particular function call has been taking too long so that we want to terminate it?</p>
  
  <p>On top of my head I think of using a thread to run that function, and kill the thread if it runs too long, as defined below:</p>
  
  <pre><code>class MyThread extends Thread
  {
    public void run()
    {
      someFunction();
    }
  }
  </code></pre>
  
  <p>And say someFunction might be:</p>
  
  <pre><code>public void someFunction()
  {
    // Unknown code that could take arbitrarily long time. 
  }
  </code></pre>
  
  <p>In the code above, <code>someFunction()</code> might take no time to finish, or takes forever, so say I want to stop it when it's taking too long. </p>
  
  <p>However, in a Java thread implementation, apparently I can't use a shared variable or any timestamp in the thread so that the thread will have a sense of time, because <code>someFunction()</code> funs atomically and such check-against-timestamp code can only go after <code>someFunction</code>, thus becoming useless since at the point of the coding being executed, someFunction is already done. </p>
  
  <p>NOTE that I also want to do so with <code>someFunction()</code> being agnostic. That is, <code>someFunction()</code> shouldn't
  be worrying about how much time it runs. It simply shouldn't be aware of it at all. </p>
  
  <p>Can anyone provide some insight in how I can accomplish this functionality? </p>