0

Possible Duplicate:
How to timeout a thread

I am using a function call to make a recursive search in a tree. It sets the best answer in a class variable and the function itself doesn't return anything.

So I want to limit the allowed time for the function. If the time has run out it simply stops and the thread is destroyed. How should I do if I want to limit the call to two seconds:

runFunction(search(),2000);
Community
  • 1
  • 1
user1506145
  • 5,176
  • 11
  • 46
  • 75

1 Answers1

1

Assuming you are using Java 5 or greater, I would use the ExecutorService interface and the submit method:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(new Runnable() {

@Override
public void run() {
    search();
    }
});
try {
    future.get(2000, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    // handle time expired
}

Using this method, you can also adjust your thread to return a value by submitting a Callable instead of a Runnable.

Richard
  • 9,972
  • 4
  • 26
  • 32