Why can't Java constructors be synchronized?

前端 未结 9 1484
甜味超标
甜味超标 2020-11-29 18:20

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating

9条回答
  •  时光说笑
    2020-11-29 18:49

    In your example, the constructor is only actually called once from one thread.

    Yes, it is possible to get a reference to an incompletely constructed Object (some discussions around double check locking and why it is broken reveal this problem), however, not by calling the constructor a second time.

    Syncronized on the constructor would prevent two threads from calling the constructor on the same Object simultaneously, and that is not possible, as it is never possible to call the constructor on an object instance twice, period.

提交回复
热议问题