I\'ve found one of the code on Stack Overflow and I thought it is pretty similar to what I am facing but I still don\'t understand why this would enter a deadlock. The examp
synchronized
places a lock on the object that must be acquired before the methods or codeblocks can execute. Because it locks entire objects, it is an inelegant tool that sometimes looks pretty easy to use, but gives deadlocks like this, where no actual contested data is being read or written.
a.method(b)
locks the a
object. b.method(a)
locks the b
object. And neither thread of execution can continue on to calling b.last()
or a.last()
, because they are both waiting for the other object to release its lock.