开发者

Synchronizing on library/third-party classes?

开发者 https://www.devze.com 2023-02-13 11:44 出处:网络
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 its

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消