Dead Lock:

two or more threads are blocked forever, waiting for each other.

class DeadlockDemo extends Thread { 
    static Thread mainThread; 

    public void run() { 
        System.out.println("Child Thread waiting for main thread completion"); 
        try { 
            // Child thread waiting for completion 
            // of main thread 
            mainThread.join(); 
        } catch (InterruptedException e) { 
            System.out.println("Child thread execution completes"); 
        } 
    } 

    public static void main(String[] args) throws InterruptedException { 
        DeadlockDemo.mainThread = Thread.currentThread(); 
        DeadlockDemo thread = new DeadlockDemo(); 

        thread.start(); 
        System.out.println("Main thread waiting for Child thread completion"); 

        // main thread is waiting for the completion 
        // of Child thread 
        thread.join(); 

        System.out.println("Main thread execution completes"); 
    } 
}

Dead Lock Prevention:

  1. lock ordering: sure that all locks are always taken in the same order by any thread, deadlocks cannot occur
  2. Lock Timeout: if thread doesn't get all lock within a certain amount of time, it releases all locks, wait for a random time and then retry.
  3. deadlock detection: complex machanism

Live Lock

Thread X responds to Thread Y, Thread Y responds to Thread X. Threads are not blocked, but they don't make progress.

results matching ""

    No results matching ""