Can we call synchronized method of an object inside the constructor of the object in Java?

Major :

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.

davidxxx :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74569&siteId=1