1

I'm learning synchronized keyword in Java, but I didn't find example using it like this: what would happen if I synchronized on another class object

public class ClassA {
  public static void hello() {
    synchronized(ClassB.class) {
      // do something
    }
  }
}
TankZhuang
  • 21
  • 2
  • 2
    Nothing special. All you're doing is synchronizing on the `java.lang.Class` instance returned by `ClassB.class`. – Slaw Jan 08 '21 at 06:12

2 Answers2

1

I may be not right. But, as I understand, if you use this class object only once, it does not change anything. If you add another method and use

synchronized(ClassB.class) {
      // do something
}

again inside the second method, than you will be able to access one code snippet inside the synchronized structure, at a time, because you will have used this class object to ensure synchronization and it will not allow simultaneous access.

1

Every object in java has a header with some meta-information fields. One of these fields is monitor, locking-counter. When you enter the protected (synchronized) section monitor's counter increments. If a different thread tries to complete your synchronized section and discovers the monitor's counter != 0 that thread will lock, until counter is no longer = 0. Which object's monitor (or classes monitor if your method is static) you want to use for synchronization is your choice. You should understand what order of lock you want.

Besides you should understand, if you use ClassB for synchronizing ClassA's methods, when will be run synchronized with help ClassB's monitor in ClassA all synchronized methods in ClassB will be waiting (if they will take synchronization by synchronized(ClassB.class)).

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Dmitrii B
  • 2,672
  • 3
  • 5
  • 14