classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Bug 2685


From: David Holmes
Subject: RE: Bug 2685
Date: Mon, 28 Jul 2003 10:42:23 +1000

Brian,

Try the attached code instead - which properly synchronizes between
the two threads to ensure that the thread to be stopped actually
starts executing. From what I observed the thread never got a chance
to run and so was stopped before it really got started. This can
happen because:

a) start sets the isAlive flag such that isAlive returns true (it need
not do this, but it can)
b) your while loop sees the thread is alive, even though it has never
yet been scheduled, and so the main thread doesn't sleep
c) you immediately stop() it, hence it will never be scheduled

Always use wait/notify to coordinate threads never use sleeps. Also
note:

a) the shared flag 'death' must be volatile as it is accessed without
synchronization

b) using someThread.sleep(x) is at best misleading because
Thread.sleep always applied to the current thread. Best to avoid
potential misunderstanding by just using Thread.sleep(x);

But also be aware that there is no guarantee, now that it is
deprecated, that Thread.stop() will do anything reasonable under the
JDK.

Cheers,
David Holmes
-----------------------------

public class stop extends Thread
{
  static volatile boolean death = false;

    static void check(boolean cond, String msg) {
        if (!cond) throw new Error(msg);
    }

    static Object lock = new Object();
    static boolean running = false;

  public void run()
  {
   System.out.println("Running ...");
   try  {
       // main thread is waiting for us to start so let it proceed
       // once we block
       synchronized(lock) {
           running = true;
           lock.notify();
       }
       synchronized (lock) {
           while (true) { lock.wait(); }
       }
   }
   catch (Exception m)
   {
       check(false, "Unexpected exception during test");
   }
   catch (ThreadDeath e)
   {
       death = true;
       Thread thread = Thread.currentThread();
       ThreadGroup group = thread.getThreadGroup();
       check(group != null, "Stop should not remove thread from
ThreadGroup");
       throw e;
   }
  }

  public static void main (String[] args)
  {

    try
      {
        Thread current = Thread.currentThread();
        ThreadGroup group = current.getThreadGroup();

        stop t = new stop();
        t.start();
        // wait until t says it's running
        synchronized(lock) {
            while (!running) lock.wait();
        }
        t.stop();
        t.join(0);
        check(death, "ThreadDeath not properly thrown and caught");
      }
    catch (InterruptedException ie)
      {
        check(false, "Unexpected interrupt");
      }
  }
}





reply via email to

[Prev in Thread] Current Thread [Next in Thread]