Synchronizing on library/third

In Java, is it generally considered safe to explicitly synchronize on an object of a class type you didn't write? I ask this because it seems that if that object internally tries to synchronize on itself, then there could potentially be an unintended deadlock between another thread trying to use a non-synchronized method of that object that internally acquires the object's monitor and the thread explicitly acquiring the lock on the object. I've never heard or read anything saying this is a bad idea, though it seems that it could be.


Java allows you to do this, but DON'T. You should work very hard to encapsulate locking within a class, or within the smallest unit possible.

Locking on an object you don't own and understand completely can cause deadlocks and other confusion.

Take a look at this question and think about how it applies to locking on third-party objects.

Also, the obligatory reference to JCiP -- Read Java Concurrency in Practice for a comprehensive, readable, and high-quality discussion of how to construct concurrent programs.


I think the answer to this question comes down to trust. Do you trust the class writer to write their objects in such a way that the problem you mention doesn't happen? If yes, go for it. If no, then you have already given the example of the time this could cause a problem.

If "it seems it could be a bad idea", it probably is. Threading is fickle, and unless you can prove it's correct, it very likely isn't (unless completely by accident).

If it were me, I would be conservative, and not synch on an object that I didn't control completely, so I could be certain that it's correct, with no guesswork.

链接地址: http://www.djcxy.com/p/64252.html

上一篇: 实现单身设计模式作为模板

下一篇: 同步库/第三