i have to write a "WatchDog" in Java, who secure that Threads don't perform too long. With the initialization of the Objects it's no Problem, i made a Class, who calls the WatchDog and the constructor with reflections in the run() method.
A Thread is easy to stop, but how i can secure normal methods of objects? For example i call the method of an Object and this method perform a endless loop, how you would do that?
thanks
First, I should point out that stopping a thread is NOT easy. In fact, in the general case, threads cannot be stopped safely:
You can call Thread.interrupt()
on a thread the you want to stop, but there is no guarantee that the thread will notice the interrupt, let alone actually stop.
You can call the deprecated Thread.stop()
method, but this method is unsafe. If you call it at an unfortunate moment, you can leave data structures in a half-updated state, leave other threads waiting (for ever) on signals that won't arrive and so on.
Here's how I'd implement a watchdog for method execution.
First I'd modify the method to add two calls to the watchdog service; e.g.
public void someMethod(...) {
Watchdog.startMethod(maxTime);
// do stuff
Watchdog.endMethod();
}
Next, I'd implement the Watchdog with a priority queue ordered on expiry time:
startMethod(maxTime)
would add an entry to the queue with expiry time of now + maxTime
. The entry would include a reference to the current thread (when the method was called.endMethod()
would look for a (the) queue entry for the current thread, and remove it if found.Some thought would need to be given to the data structures, and to dealing with cases where endMethod
calls get skipped. (Indeed, since a method call can terminate due to an exception, the endMethod()
call really needs to be done in a finally
block.)
Note that the startMethod
and endMethod
calls could (and maybe should) be inserted by an annotation processor or something like that.
Given the complexity, and the fact that you can't guarantee to stop the thread (safely), I'd think of some solution that doesn't involve a method watchdog.
Normal methods of objects are running on some thread. It might be the AWT event dispatcher or whatever it's called. Or it might be the main thread, say, of a console application.
They are no different to the threads that are called with new Thread().
I guess your watchdog needs to be looking at all the threads in the VM and looking for ones which have a utilisation >= some threshold.
What code do you have so far?
Rich
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With