I’m modifying a bit of seriously complex code and I need to add my own synchronization on top of this.
However, the existing code has about a dozen, if not more, different locks, and my code needs to call some of its methods. I don’t really know the order in which the locks are being obtained, nor can I really control it.
So, my question is, what would happen if I replaced all the different locks by a single lock?.Apart from sacrificing granularity, is there any other issue I should be aware of?
Thanks!
If you change all of the
synchronizedblocks (and methods), and all the other blocking structures, I think you should be fine — worst case, your app degenerates to having serial execution. But if you only change some of them, you could get deadlock. Consider a scenario where two threads are each acquiring multiple locks:There’s no risk of deadlock here, but if you replace
AandC(but notB) with the new, common lock, then you’ll have:… which is the classic deadlock case.
Consider another scenario, where the locks don’t provide deadlock themselves, but instead deadlock a blocking class like a CountDownLatch:
In this case, changing both
synchronizedblocks to lock on a common lock won’t cause deadlock between them, but will cause deadlock if thread 2 gets the lock first: it’ll await the latch’s countDown, which will never come because thread 1 is blocked at itssynchronizedentry point. This example applies to other blocking structures, too: semaphores, blocking queues, etc.