I am not sure I fully understand your problem. This "thread" goes off
in all kind of directions (which is not uncommon here) except
discussing the problem you raise :-(
Though stop is deprecated, I think the reasons are overly politically
correct. If the reasons were valid, then any unchecked exception are
mortal. From my experience, this leaves very few systems. One of the
good parts of Java is that it does not die when it gets in a bad state.
Especially in cases like you discuss where no lifes or great finanical
risks are at stake, Thread.stop can have a role. I think SUN, as a
litigatious sensitive company, deprecated it (though it has NOT removed
it!).
I understand your key problem is that your notification is not waking
up the wait. I deduce that you you run the student code in a
try/finally clause and notify in the finally clause you so your main
thread wakes up? I.e. something like this:
public class Runner extends Thread {
Runnable student;
static Timer timer = new Timer();
Runner(Runnable student) {
this.student = student;
}
public void run() {
try {
student.run();
}
finally {
synchronized (this) {
System.out.println("Notifying");
notifyAll();
}
}
}
public static void main(String args[]) throws Exception {
Runnable student = new BadStudent();
final Runner runner = new Runner(student);
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Timed out, stopping");
runner.stop();
}
};
timer.schedule(task, 5000);
System.out.println("Starting runner");
runner.start();
synchronized (runner) {
runner.wait();
System.out.println("Received notification");
}
task.cancel();
}
}
class BadStudent implements Runnable {
double sum;
public void run() {
System.out.println("Starting bad student");
try {
double start=1;
while (true ) {
start /= 2;
sum += start;
}
} finally {
System.out.println("Leaving bad student");
}
}
}
Running it:
Starting runner
Starting bad student
Timed out, stopping
Leaving bad student
Notifying
Received notification
I tried this on my system and it works ok. Can you elucidate what you
do different? Show some code? Did I misunderstand you?
Running the code in a Threadgrouped Thread, its own classloader, and
then using stop for this example should give you a system that can
handle most of the student's abuses. You could even deny catching
ThreadDeath which is an easy trick.
An alternative is to use Aspect Oriented Programming. You could write
aspects that insert checks in the students code to quit in every method
and loop (I am not sure if you write an advice for a loop though). You
could also use ASM and just insert a check before every jump I guess.
Kind regards,
Peter Kriens
OSGi Evangelist
www.osgi.org and
www.aqute.biz