Search code examples
javamultithreadingconcurrencyterminate

How to limit a thread's execution time and terminate it if it runs too long?


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?

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:

class MyThread extends Thread
{
  public void run()
  {
    someFunction();
  }
}

And say someFunction might be:

public void someFunction()
{
  // Unknown code that could take arbitrarily long time. 
}

In the code above, someFunction() might take no time to finish, or takes forever, so say I want to stop it when it's taking too long.

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 someFunction() funs atomically and such check-against-timestamp code can only go after someFunction, thus becoming useless since at the point of the coding being executed, someFunction is already done.

NOTE that I also want to do so with someFunction() being agnostic. That is, someFunction() shouldn't be worrying about how much time it runs. It simply shouldn't be aware of it at all.

Can anyone provide some insight in how I can accomplish this functionality?


Solution

  • I would use an ExecutorService to run the thread. Then I would get back a Future and use get() with a timeout to cancel it.

    ExecutorService es = Executors.newFixedThreadPool(1); // You only asked for 1 thread
    Future<?> future = es.submit( new Mythread() );
    try {
        future.get(timeout, TimeUnit.SECONDS); // This waits timeout seconds; returns null
    } catch(TimeoutException e) {
        future.cancel(true);
    }