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.