Why can't Java constructors be synchronized?

前端 未结 9 1480
甜味超标
甜味超标 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:41

    Such a synchronization might make sense in some very rare cases, but I guess, it's just not worth it:

    • you can always use a synchronized block instead
    • it'd support coding in a pretty strange way
    • on what should it synchronize? A constructor is a sort-of static method, it works on an object but gets called without it. So synchronizing on the class also makes (some) sense!

    When in doubt, leave it out.

提交回复
热议问题