Search code examples
javamultithreadingtimeoutthreadpool

How to avoid disorder when calling future.cancel()?


Here is the thing.

First, I have a thread pool in java (e.g., a thread pool has 8 threads).

Second, I have another monitor thread to limit that the execution time of each thread in this pool cannot be larger than 5 minutes via future.cancel() method.

However, I figure out a potential disorder under the situation below.

Assume, thread t1 in this pool has executed over 5 minutes, and monitor thread has observed this situation. At the same time, thread t1 finished its current computation task and accepted another new computation task; monitor thread calls future.cancel() to send the interrupt signal to thread t1.

Unfortunately, thread t1 checks its interrupt signal and cancel this new task, which is not our expectation.

The question is how to avoid this situation? Any advice?


Solution

  • Seems that you need some kind of "atomic" cancellation of task. But I don't know if this is possible, so I have another idea:

    You can inverse logic, so Monitor will check the time of execution, then set some kind of "flag" in thread. And thread can check this flag in it's logic of task execution.