We can not make constructor synchronized
but can write synchronized
this inside constructor. In what case such requirement will come ?
I am amused.
package com.simple;
public class Test {
public Test() {
synchronized (this) {
System.out.println("I am called ...");
}
}
public static void main(String[] args) {
Test test=new Test();
System.out.println(""+test);
}
@Override
public String toString() {
return "Test []";
}
}
Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.
Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.
A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block.
Well, you could start a new thread within the constructor. It would be highly unusual - and certainly in the code you've provided it would be pointless - but it could happen.
Languages don't typically try to find every possibly thing you could do that would be pointless - it would lead to a very complex language specification. There has to be some degree of thought on the part of the language users, too...
Synchronizing on this
would be a sign of bad practice because it would imply you are leaking this
out of the constructor: this is the only way you could have some other code synchronizing on the same object.
Synchronizing on some other common lock, however, could be legitimate: the constructor my indeed involve calling some code that requires such synchronization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With