3

I have a Java method that does sampling. That is, it does something like this:

TIME = 60 /* seconds */

startTime = now();
count = 0;
while (now() - startTime < TIME) {
    sample = createRandomSample();
    if (satisfiesSomeConditions(sample)) {
       count++;
    }
}

return count;

Now, usually, createRandomSample() and satisfiesSomeConditions(sample) run pretty fast (as in a second or less), so this code works well.

However, once in a while, one of these functions might take a long time to run. How can I control this sampling process to run not much longer than requested by TIME. I don't mind if it runs, say, 10% longer than TIME, but I don't want it running for some arbitrarily long amount of time over TIME.

An ExecutorService seems too harsh.

It's more like we want to run the sampling on a separate thread and then gently tell that thread to stop sampling and give whatever results it currently has.

Paul Reiners
  • 8,576
  • 33
  • 117
  • 202

1 Answers1

1

You could use a FutureTask. Something like this:

FutureTask<Void> futureTask = new FutureTask<Void>(new Callable<Void>() {
    @Override
    public Void call() throws Exception {
        doStuff();
        return null;
    }
    });
futureTask.run();
futureTask.get(60, TimeUnit.SECONDS); //handle exceptions

The get() method terminates when the callable is done. If that happens before the timeout, everything is fine. If not, it throws a TimeoutException which you have to catch in this case.

eboix
  • 5,113
  • 1
  • 27
  • 38
Anna
  • 283
  • 2
  • 9