Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 403
Major Avatar asked Mar 03 '23 20:03

Major


1 Answers

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.

like image 62
davidxxx Avatar answered Mar 06 '23 10:03

davidxxx