SlideShare a Scribd company logo
1 of 14
Deadlocks




            1
Objectives

On completion of this period, you would be able
to learn

  •   Deadlock problem
  •   Threads and deadlock
  •   Example Java program
  •   Avoiding deadlock




                                                  2
Recap

In the previous class, you have learnt

•   Inter thread communication methods
•   About wait() method
•   About notify() method
•   Producer-Consumer problem
•   Solution to Producer–Consumer problem




                                            3
Deadlock Problem
• A set of blocked processes each holding a resource
  and waiting to acquire a resource held by another
  process in the set
• Example
  • System has 2 tape drives
  • P1 and P2 each hold one tape drive and each needs another
    one
• Example
  • semaphores A and B, initialized to 1
            P0            P1
          wait (A);             wait(B)
          wait (B);             wait(A)
                                                                4
Bridge Crossing Example



         Fig. 39.1 Bridge crossing example for deadlock

• Each section of a bridge can be viewed as a
  resource
• If two cars in each section of the bridge try to
  cross the bridge at the same time, deadlock
  occurs
• If a deadlock occurs, it can be resolved if one car
  backs up (preempt resources and rollback)
• Several cars may have to be backed up if a
  deadlock occurs
• Starvation is possible
                                                          5
Threads and Deadlock
• Occur when threads are mutually blocking each
  other
• Not normally detected by Java Runtime
• Should be avoided by design
• Example :
                                                             Blocks object B
Blocks object A



                           Deadlock
                                                            Blocks object A
Blocks object B
                      Fig. 39.2. Illustration of Deadlock
                                                                              6
Example Program
class A {
    synchronized void method1(B b) {
         String name = Thread.currentThread().getName();
         System.out.println(name + " entered A. method1");
         try {
                   Thread.sleep(1000);
         } catch(Exception e) {
                   System.out.println("A Interrupted");
         }
         System.out.println(name + " trying to call B.last()");
         b.last();
  }                                          A call to another synchronized
  synchronized void last() {                 method of B
         System.out.println("Inside A.last");
  }
}

                                                                              7
Example Program
     class B {
      synchronized void method2(A a) {
            String name = Thread.currentThread().getName();
            System.out.println(name + " entered B. method2");
            try {
                      Thread.sleep(1000);
            } catch(Exception e) {
                      System.out.println("B Interrupted");
            }
            System.out.println(name + " trying to call A.last()");
            a.last();
                                                A call to another synchronized
    }
                                                method of A
    synchronized void last() {
            System.out.println("Inside B.last");
    }
}


                                                                                 8
Example Program
                                                        Contd . . .
class Deadlock implements Runnable {
  A a = new A(); B b = new B();                      Objects of A and B with
  Deadlock() {                                       methods method1() and
                                                     method2() are created
    Thread.currentThread().setName("MainThread");
    Thread t = new Thread(this, "RacingThread"); These methods pause
    t.start();                                       briefly and call each other
                                                     through last() method
    a. method1(b); // get lock on a in this thread.
    System.out.println("Back in main thread");        As all these methods are
  }                                                  synchronized,
                                                          DEADLOCK
  public void run() {
                                                      occurs
    b. method2(a); // get lock on b in other thread.
    System.out.println("Back in other thread");
  }
  public static void main(String args[]) { new Deadlock(); }
                                                                                   9
}
Avoiding Deadlock
• Avoid having code in a restricted area that can
  halt thread
• If multiple locks are required, request the locks in
  the same order

• Example




                   Fig. 39.3 Avoiding Deadlock

                                                         10
Summary

• In this class, you have learnt

   •   The deadlock problem
   •   An illustration for deadlock
   •   Example program to show deadlock
   •   A technique to avoid deadlock


• In the next lesson we look at Thread properties



                                                    11
Quiz

1. A deadlock is caused by calling

  A.   A wait() method
  B.   Mutually blocking statements
  C.   A notify() method
  D.   A notifyAll() method




                                      12
Quiz Contd..

2. While in deadlock, threads will be

  A.   Executing properly
  B.   Sleeping for specified time
  C.   Blocked ( not doing any work)
  D.   Waiting for a given time




                                        13
Frequently Asked Questions

1. Define deadlock
2. Explain deadlock with examples
3. How to avoid deadlock ?




                                      14

More Related Content

What's hot

Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Ciklum Minsk
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadPropertiesmyrajendra
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

What's hot (20)

Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadProperties
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java memory model
Java memory modelJava memory model
Java memory model
 
Threads
ThreadsThreads
Threads
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2
 
Java
JavaJava
Java
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 

Similar to Dead locks9cm604.39

Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)It Academy
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36myrajendra
 
Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Jigar Maheshwari
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdfMohit Kumar
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 

Similar to Dead locks9cm604.39 (20)

Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Java session13
Java session13Java session13
Java session13
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36
 
Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Java class 6
Java class 6Java class 6
Java class 6
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Java Threads
Java ThreadsJava Threads
Java Threads
 

More from myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Dead locks9cm604.39

  • 2. Objectives On completion of this period, you would be able to learn • Deadlock problem • Threads and deadlock • Example Java program • Avoiding deadlock 2
  • 3. Recap In the previous class, you have learnt • Inter thread communication methods • About wait() method • About notify() method • Producer-Consumer problem • Solution to Producer–Consumer problem 3
  • 4. Deadlock Problem • A set of blocked processes each holding a resource and waiting to acquire a resource held by another process in the set • Example • System has 2 tape drives • P1 and P2 each hold one tape drive and each needs another one • Example • semaphores A and B, initialized to 1 P0 P1 wait (A); wait(B) wait (B); wait(A) 4
  • 5. Bridge Crossing Example Fig. 39.1 Bridge crossing example for deadlock • Each section of a bridge can be viewed as a resource • If two cars in each section of the bridge try to cross the bridge at the same time, deadlock occurs • If a deadlock occurs, it can be resolved if one car backs up (preempt resources and rollback) • Several cars may have to be backed up if a deadlock occurs • Starvation is possible 5
  • 6. Threads and Deadlock • Occur when threads are mutually blocking each other • Not normally detected by Java Runtime • Should be avoided by design • Example : Blocks object B Blocks object A Deadlock Blocks object A Blocks object B Fig. 39.2. Illustration of Deadlock 6
  • 7. Example Program class A { synchronized void method1(B b) { String name = Thread.currentThread().getName(); System.out.println(name + " entered A. method1"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("A Interrupted"); } System.out.println(name + " trying to call B.last()"); b.last(); } A call to another synchronized synchronized void last() { method of B System.out.println("Inside A.last"); } } 7
  • 8. Example Program class B { synchronized void method2(A a) { String name = Thread.currentThread().getName(); System.out.println(name + " entered B. method2"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("B Interrupted"); } System.out.println(name + " trying to call A.last()"); a.last(); A call to another synchronized } method of A synchronized void last() { System.out.println("Inside B.last"); } } 8
  • 9. Example Program Contd . . . class Deadlock implements Runnable { A a = new A(); B b = new B(); Objects of A and B with Deadlock() { methods method1() and method2() are created Thread.currentThread().setName("MainThread"); Thread t = new Thread(this, "RacingThread"); These methods pause t.start(); briefly and call each other through last() method a. method1(b); // get lock on a in this thread. System.out.println("Back in main thread");  As all these methods are } synchronized, DEADLOCK public void run() { occurs b. method2(a); // get lock on b in other thread. System.out.println("Back in other thread"); } public static void main(String args[]) { new Deadlock(); } 9 }
  • 10. Avoiding Deadlock • Avoid having code in a restricted area that can halt thread • If multiple locks are required, request the locks in the same order • Example Fig. 39.3 Avoiding Deadlock 10
  • 11. Summary • In this class, you have learnt • The deadlock problem • An illustration for deadlock • Example program to show deadlock • A technique to avoid deadlock • In the next lesson we look at Thread properties 11
  • 12. Quiz 1. A deadlock is caused by calling A. A wait() method B. Mutually blocking statements C. A notify() method D. A notifyAll() method 12
  • 13. Quiz Contd.. 2. While in deadlock, threads will be A. Executing properly B. Sleeping for specified time C. Blocked ( not doing any work) D. Waiting for a given time 13
  • 14. Frequently Asked Questions 1. Define deadlock 2. Explain deadlock with examples 3. How to avoid deadlock ? 14