title: Java function ending after time has elapsed
body: <p>Here's what I want to do. Given a function</p>
  
  <pre><code>public void foo() {
  
  }
  </code></pre>
  
  <p>I would like to have it end after certain time has elapsed. That is, imagine this is some kind of random generator which has to produce random objects that satisfy some difficult constraints and hence it may or may not succeed under a given time allotment. That is, the function may actually be something like this</p>
  
  <pre><code>public void foo() {
     //task1
     while(fails) {
       //...
     }
  
     //task2
     while(fails2) {
        //...
     }
  
     //more tasks may follow, which use the data from the previous tasks to further try to satisfy difficult conditions
  }
  </code></pre>
  
  <p>That is simply just an example. But the point is that the function consists of many while loops, many test cases, and lots of heavy computation.</p>
  
  <p><strong>The goal:</strong> I want to be able to say "run foo() and if 4 seconds has elapsed and foo() is still not done, then stop foo() immediately."</p>
  
  <p><strong>What I have tried:</strong> I have tried to include conditions on just about every line of foo() to see how much time has elapsed and to return out of the function if the 4 seconds has passed. But given how complicated foo() is, this is clearly very difficult to do code wise because this requires testing the time on every single line of the function. </p>
  
  <p><strong>My thought logic:</strong> I think this should be possible because there are functions that do this sort of thing, that terminate code regardless of the state, such as System.exit(1). That is the idea. I'd like to be able to call, from the outside, to have this function foo() terminate.</p>