Java synchronized seems ignored

Posted by viraptor on Stack Overflow See other posts from Stack Overflow or by viraptor
Published on 2010-03-23T12:38:42Z Indexed on 2010/03/23 12:43 UTC
Read the original article Hit count: 495

Hi, I've got the following code, which I expected to deadlock after printing out "Main: pre-sync". But it looks like synchronized doesn't do what I expect it to. What happens here?

import java.util.*;

public class deadtest {
   public static class waiter implements Runnable {
      Object obj;

      public waiter(Object obj) {
         this.obj = obj;
      }

      public void run() {
         System.err.println("Thead: pre-sync");
         synchronized(obj) {
            System.err.println("Thead: pre-wait");
            try {
               obj.wait();
            } catch (Exception e) {
            }
            System.err.println("Thead: post-wait");
         }
         System.err.println("Thead: post-sync");
      }
   }

   public static void main(String args[]) {
      Object obj = new Object();

      System.err.println("Main: pre-spawn");

      Thread waiterThread = new Thread(new waiter(obj));
      waiterThread.start();

      try {
         Thread.sleep(1000);
      } catch (Exception e) {
      }  

      System.err.println("Main: pre-sync");
      synchronized(obj) {
         System.err.println("Main: pre-notify");
         obj.notify();
         System.err.println("Main: post-notify");
      }
      System.err.println("Main: post-sync");

      try {
         waiterThread.join();
      } catch (Exception e) {
      }
   }
}

Since both threads synchronize on the created object, I expected the threads to actually block each other. Currently, the code happily notifies the other thread, joins and exits.

© Stack Overflow or respective owner

Related posts about java

Related posts about synchronization