Constructor in java cannot be synchronized


Contents of page :
  • Enclosing constructor in synchronized block will generate compilation error >
  • Using synchronized in constructor definition will also show compilation error >
  • Though we can use synchronized block inside constructor >


No, constructor cannot be synchronized. Because constructor is used for instantiating object, when we are in constructor object is under creation. So, until object is not instantiated it does not need any synchronization.



Enclosing constructor in synchronized block will generate compilation error >
Any attempt to do so is against java coding syntax.



Using synchronized in constructor definition will also show compilation error >
COMPILATION ERROR = Illegal modifier for the constructor in type ConstructorSynchronizeTest; only public, protected & private are permitted



Though we can use synchronized block inside constructor >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConstructorSynchronizeTest {
  
   //constructor
   public ConstructorSynchronizeTest() {
          synchronized (this) {
                 //...Here you can write your thread safe code...
          }
   }
  
}



RELATED LINKS>


Thread Starvation

Constructor in java cannot be synchronized

ThreadLocal in multithreading in java - methods and usage with program

Busy Spin - What is busy spin? Consumer Producer problem with busy spin and solution to busy spin.

ThreadGroup in java


eEdit
Must read for you :