20-CS-4003-001 Organization of Programming Languages Fall 2017
Threads and Deadlock

Lambda calculus, Type theory, Formal semantics, Program analysis

All lectures
Use of synchronized, notify, wait

    1.   DeadLock.java

  -   Attempt at a simple handshake. Girl pings Boy, gets confirmation. Then Boy pings girl, get confirmation. Girl thread invokes ping, asks Boy to confirm. But Boy invokes ping, and asks Girl to confirm. Neither Boy nor Girl can give time to their confirm call because they are stuck in ping. Hence the handshake cannot be completed.
    2.   DeadLockFixed.java

  -   The handshake is reliable now. Girl pings Boy, gets confirmation. Then Boy pings girl, get confirmation. The Girl and Boy invoke their ping. One of the two reaches other.release() first but since the other thread has not even entered its ping, no thread is released. The first thread continues to the try-catch and waits before invoking p.confirm(). This allows the other thread to enter its ping. That thread wakes up the first thread by invoking other.release(). It then continues to the try-catch block and waits. Since the first thread is now awake, it gets run time and invokes p.confirm(). Since the other thread is waiting, the first thread enters the other thread's monitor and invokes the confirm. The confirm returns and the first thread continues to other.release(). The other thread awakens and continues to p.confirm(). Since there is no thread that owns the first thread's monitor, confirm completes and the other thread continues to other.release() where nothing happens and the handshake ends.