Is it useful to have a dedicated object for a lock? [duplicate]

前提是你 提交于 2019-12-10 21:21:05

问题


I am cleaning up a legacy java code and I found following construct:

final class QuiteComplexClass {
    private Object lock = new Object();

    void aMethod() {
        ...
        synchronized(lock) {
              ....
        }
    }
}

Is the special object for locking necessary here? What is difference when I used simple synchronized (this)?

I think it might by useful when the class is publicly visible and somebody may call synchronized on the class instance by mistake. But this class is package private so no external code can do that.


回答1:


Is the special object for locking necessary here? What is difference when I used simple synchronized (this)?

Short answer: no, it's not necessary but aside from adding final I see little to no benefit to remove it.

I tend to like to use locking objects because they give me a more fine grained lock as opposed to locking on this. You might have a couple different lock objects in your class if you are, for example, protecting multiple collections from race conditions. One thing to sure is that you should always make sure to make the lock field final.

private final Object lock = new Object();

This said, if a class is simple and you want to make sure people know which methods are synchronized then using the keyword on the methods is very appropriate as well. As you mentioned, this is an internal class but even then, developers working on the outer class might want to know about the sync points.




回答2:


The difference is that if you use this as lock or mark method as synchronized then another piece of code could accidentally (or intentionally) use your QuiteComplexClass object as a lock. And it might cause your code to work incorrectly. If some other developer decides to write the code as below then your code will not be able to call synchronized methods on qcc instance while lock is being held.

synchronized(qcc) { // assuming qcc is an instance of QuiteComplexClass
   while (true); // or any other time consuming operation
}



回答3:


No, it's unnecessary. Using a lock object is a pattern intended to avoid locking on the instance. Whether that is valuable often is a matter of opinion.



来源:https://stackoverflow.com/questions/50138378/is-it-useful-to-have-a-dedicated-object-for-a-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!