6

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.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • the object won't try to synchronize on itself out of nowhere (unless your 3rd-party API is *a)* spawning threads and *b)* doing very weird stuff). Basically the problem happens when **you** will make what is called an *"alien method call"*. In Effective Java it is explained that you should never make alien method calls with a lock held. – SyntaxT3rr0r Feb 27 '11 at 15:28

2 Answers2

2

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.

Community
  • 1
  • 1
andersoj
  • 22,406
  • 7
  • 62
  • 73
0

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.

nrobey
  • 705
  • 4
  • 12