Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Synchronized Block for .class

People also ask

Can we use synchronized for class in Java?

The synchronized keyword can only be used on method declarations and as synchronized blocks. When used on a method declaration, it's the same as adding a synchronized block around the contents of the method, synchronizing on this . There is nothing preventing you from synchronizing every method of a class.

How do you create a synchronized block to get class level lock?

If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock.

What is synchronized class?

synchronized(X. class) is used to make sure that there is exactly one Thread in the block. synchronized(this) ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instance synchronized(this) is enough.


The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block.

With synchronized(this) the block is guarded by the instance. For every instance only one thread may enter the block.

synchronized(X.class) is used to make sure that there is exactly one Thread in the block. synchronized(this) ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instance synchronized(this) is enough.


To add to the other answers:

static void myMethod() {
  synchronized(MyClass.class) {
    //code
  }
}

is equivalent to

static synchronized void myMethod() {
  //code
}

and

void myMethod() {
  synchronized(this) {
    //code
  }
}

is equivalent to

synchronized void myMethod() {
  //code
}

No, the first will get a lock on the class definition of MyClass, not all instances of it. However, if used in an instance, this will effectively block all other instances, since they share a single class definition.

The second will get a lock on the current instance only.

As to whether this makes your objects thread safe, that is a far more complex question - we'd need to see your code!