ไม่สามารถ Constructor ไม่สามารถเป็น synchronized ใน Java JVM รับประกันว่าในเวลาเดียวกันจะมีเพียงเธรดเดียวที่เรียก constructor ได้ ดังนั้นไม่ต้องประกาศ synchronized และเป็น ผิดกฎหมาย (illegal) ใน Java แต่เราสามารถใช้ synchronized blocks ภายใน constructor ได้
หากพยายามวาง synchronized keyword หน้า constructor คอมไพเลอร์จะบอกว่า "error: modifier synchronized not allowed here"
ตัวอย่าง
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();
}
}
ผลลัพธ์
SynchronizedConstructorTest.java:3: error: modifier synchronized not allowed here public synchronized SynchronizedConstructorTest() { ^ 1 error