First, I must point out that stopping the thread is NOT easy. In fact, in general, threads cannot be safely stopped:
You can call Thread.interrupt() on the thread that you want to stop, but there is no guarantee that the thread will notice the interrupt, not to mention the termination.
You can call the deprecated Thread.stop() method, but this method is unsafe. If you call this at an unsuccessful moment, you can leave the data structures in a state with half an update, leave other threads waiting (forever) for signals that will not arrive, etc.
Here's how I can implement a watchdog to execute a method.
First I have to change the method to add two calls to the watchdog service; eg
public void someMethod(...) { Watchdog.startMethod(maxTime);
Next, I would use Watchdog with a priority queue ordered after the expiration date:
startMethod(maxTime) will add the entry to the queue with the expiration of the time now + maxTime . The entry will include a link to the current thread (when the method was called.endMethod() will search for the queue () entry for the current thread and delete it if it is found.- The watchdog side will periodically look at the recording of the first queue. If this record ends less than now, the watchdog will delete the record, stop the stream, and check the next record. Repeat until the next recording expires.
Some thoughts should be given to data structures and to deal with cases where endMethod calls are skipped. (Indeed, since the method call may end due to an exception, the call to endMethod() should indeed be executed in the finally block.)
Note that calls to startMethod and endMethod could (and possibly should) have been inserted by an annotation processor or something like that.
Given the complexity and the fact that you cannot guarantee the stop of the stream (safely), I would think of some solution that is not related to the watchdog method.
source share