Ahmet Karakaya
Ahmet Karakaya

Reputation: 10139

Thread synchronized block with Class itself

I thought that following usage is to create a synchronized-block because ThreadMyClass.class is unique. But When I have created a heavy traffic with multiple Threads trying to access get() method, I have found out that many inconsistent states were created. So why threads are not synchronized with ThreadMyClass.class instance?

public ThreadMyClass {


 public Object  get(){

  synchronized (ThreadMyClass.class) {
    //get object return 
  }

 }
}


public static final  Object lock = new Object();

When I have changed ThreadMyClass.class with lock object , everything is working fine.

updated: here is my full code portion instance creation block is invoked more than one time.

   public static XmppInterface getInstance() throws XMPPException {
      if (instance == null) {
         synchronized (XmppInterface.class) {
            if (instance == null) {
              //create an instance
            }
         }
      }
      return instance;
   }

Upvotes: 1

Views: 227

Answers (1)

Mena
Mena

Reputation: 48404

Well, you were synchronizing over the class, not its instance, which was tantamount to having a static synchronized method.

To synchronize over the instance of your class you can use a synchronized instance method.

Otherwise, synchronizing over an Object used for a lock will synchronize on that Object only, leaving the rest of your static and instance methods "free" from the synchronization strategy in place.

Upvotes: 3

Related Questions