I am new to Java. I am wondering if it is possible to call a synchronized method inside constructor. There is the example:
class a{
int a1;
public a(){
a1 = 1;
increment();
}
private synchronized void increment(){
a1++;
}
}
It is a toy example. I can just set the a1 to 2 at the constructor. I am just confused whether we can call increment()
inside the constructor or not.
You can do that but that synchronization is meaningless because the synchronized method will lock the instance that is currently being created. But which other thread could access it while that has not still be created and returned ? No one.
Constructors are indeed defacto thread safe as long as you follow good practices such as not passing this
to other classes/objects inside the constructor body.
Your example could make more sense with a synchronized static
method or synchronized
on a static
field.
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