Can a constructor be synchronized in Java?

JavaObject Oriented ProgrammingProgramming

No, a constructor cannot be synchronized in Java. The JVM ensures that only one thread can invoke a constructor call at a given point in time. That is why no need to declare a constructor as synchronized and it is illegain Java. However, we can use synchronized blocks inside a constructor.

If we are trying to put a synchronized keyword before a constructor, the compiler says that "error: modifier synchronized not allowed here".

Example

public class SynchronizedConstructorTest {
      // declaration of synchronized constructor
      public synchronized SynchronizedConstructorTest() {
         System.out.println("Synchronized Constructor");
      }
      public static void main(String args[]) {
         SynchronizedConstructorTest test = new SynchronizedConstructorTest();
      }
}

Output

SynchronizedConstructorTest.java:3: error: modifier synchronized not allowed here
public synchronized SynchronizedConstructorTest() {
^
1 error
raja
Published on 26-Aug-2019 15:31:31
Advertisements