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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With