Avoid synchronized(this) in Java?

后端 未结 22 1176
予麋鹿
予麋鹿 2020-11-22 01:23

Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that synchronized(this) should be avoided. Instead, they c

22条回答
  •  清酒与你
    2020-11-22 02:00

    There seems a different consensus in the C# and Java camps on this. The majority of Java code I have seen uses:

    // apply mutex to this instance
    synchronized(this) {
        // do work here
    }
    

    whereas the majority of C# code opts for the arguably safer:

    // instance level lock object
    private readonly object _syncObj = new object();
    
    ...
    
    // apply mutex to private instance level field (a System.Object usually)
    lock(_syncObj)
    {
        // do work here
    }
    

    The C# idiom is certainly safer. As mentioned previously, no malicious / accidental access to the lock can be made from outside the instance. Java code has this risk too, but it seems that the Java community has gravitated over time to the slightly less safe, but slightly more terse version.

    That's not meant as a dig against Java, just a reflection of my experience working on both languages.

提交回复
热议问题