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

20
June 13, 2019, at 12:30 PM

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.

Thanks in advance!

Answer 1

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.
Your example could make more sense with a synchronized static method or synchronized on a static field.

READ ALSO
Display annotation markers in Eclipse compare editor

Display annotation markers in Eclipse compare editor

Unable to display annotation markers in Eclipse compare editor when I tried comparing two files

33
Failed startup of context o.e.j.w.WebAppContext@34cd072c

Failed startup of context o.e.j.w.WebAppContext@34cd072c

I am running Docker, the container got started but throws the below error

63
How to create an snmp trap receiver and sender that supports TSM based security model in SNMP4J?

How to create an snmp trap receiver and sender that supports TSM based security model in SNMP4J?

I'm trying to create a snmp trap receiver and sender to support snmp v3 traps using SNMP4j apiI have few resources and documentation to implement them using USM based security model but I want to use TSM based security model to support version 3 traps

56