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>