I'm trying to construct a deadlock deliberately by coding this scenario:
1) Thread A enters a synchronized method of object foo
2) Thread A goes to sleep (thus still holding the key of foo)
3) Thread B enters a synchronized method of object bar
4) Thread B tries to enter a synchronized method of foo (, but cant)
5) Thread A wakes up and tries to enter a synchronized method of bar => deadlock
I'm trying to keep the code really minimalistic, i.e. just 2 threads and 2 objects.
I also dont want to use this syntax:
but would like to achieve this just by calling synchronized methods of 2 different objects (as stated above).
I've been fumbling around for quite some time but I'm giving up now...
It may also be a good idea to add the sleep() to class B (just like class A). Depending on the scheduler, it is possible for the t2 thread to run first. This thread can acquire the B lock, and then immediately acquire the A lock. In which case ...
The t1 thread will be blocked for the A lock. The t2 thread will recursively keep acquiring both locks, until it runs out of memory, throws an exception, releases all the locks. And once all the locks are released, then t1 will do the same.