Exiting a function when it's done or after some specific time(Even it's not done) in java
<p>I need to forcefully stop a method in java after some time if it's not finished yet.I implemented this with a while loop. But it waits throughout the whole time even the function execution is done.</p>

<p>If it's finished by this time,I need the loop to be stopped.
Any suggestions would be great.</p>

<p>EDITED FROM HERE</p>

<pre><code>import java.util.concurrent.* ;

ExecutorService svc = Executors.newFixedThreadPool( 1 ) ;
svc.submit( new Runnable() {
  public void run() {
    myFunction();
  }
} ) ;
svc.shutdown() ;
svc.awaitTermination( 300, TimeUnit.SECONDS ) ;
</code></pre>

<p>I tried this code. it worked ok. But when myfunction is done/exits due to time constraints, the code remain paused for some moment.I don't know why.:(</p>
