Can a constructor be synchronized in Java?


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

Updated on: 02-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements