Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing on library/third-party classes?

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.

like image 292
templatetypedef Avatar asked Nov 14 '22 02:11

templatetypedef


1 Answers

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.

like image 176
andersoj Avatar answered Dec 18 '22 15:12

andersoj