Reputation: 8578
given a Runnable:
public class MyRunnable implements Runnable {
public void run() {
doA();
for (i=0; i<18123 ; i++) {
doB();
}
doC();
}
}
where doA,B,C are defined with like 100 lines of code each.
what is the best way to make the thread FREEZE - in whatever line of code its at - and then continue from the next line of code where it last stopped.
I was searching around the net, and I saw here http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html that they suggest on using a boolean, so, does that mean that i need to check that boolean after every few lines of code? there's gotta be a nicer way...
Upvotes: 1
Views: 280
Reputation: 54091
That cannot work in general for the cause Thread.suspend()
and Thread.resume()
have been deprecated:
Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.
If you absolutely need this behavior, you have to explicitly implemented it yourself.
The implementations could look like this (code not tested, nor compiled):
public abstract class SafeStoppableRunnable implements Runnable { private boolean stopped = false; public synchronized void stopSafe() { this.stopped = true; } public synchronized void resumeSafe() { this.stopped = false; synchronized(this) { this.notifyAll(); } } protected synchronized void waitWhenStopped() { while(this.stopped) { this.wait(); } } }
The stoppable Runnable
s should then extend SafeStoppableRunnable
and call the method waitWhenStopped()
at all the points in your program you want it to be stoppable. Stoppable points are probably points where the program does not hold global ressources other threads need to make progress.
Upvotes: 2
Reputation: 17444
Multithreaded systems are really complex. The golden rule of multithreaded programming is to avoid any code that can potentially raise the level of entropy of the system. Vague system states are impossible to predict and trace.
A thread paused at some unpredictable line is multithreaded programmer's nightmare. At development time it is simply impossible to make sure that the system will be working fine after the thread is woken up at some unknown line. You just can't keep track of all the alternatives. This will 100% result in all kind of weird defects in production.
Adding a couple of definite pause points in a thread is the only way to go.
Upvotes: 2