[Java concurrent programming] 9: deadlock (including code), java concurrency

Source: Internet
Author: User

[Java concurrent programming] 9: deadlock (including code), java concurrency

A deadlock may occur when the thread needs to hold multiple locks at the same time. Consider the following situations:

Thread A currently holds the lock1 lock and thread B currently holds the lock2 lock. Next, when thread A still holds lock1, it tries to get lock2 because thread B is holding lock2, so thread A will block waiting for thread B to release lock2. If thread B tries to obtain lock1 when holding lock2 at this time, because thread A is holding lock1, thread B will block waiting for A to release lock1. Both of them are waiting for the release of the lock held by the other party, but they have not released the lock held by themselves, then the two will continue to block. This situation is called a deadlock.

The following is an example of a deadlock between two threads:

[Java]View plaincopy
  1. Public class Deadlock extends Object {
  2. Private String objID;
  3. Public Deadlock (String id ){
  4. ObjID = id;
  5. }
  6. Public synchronized void checkOther (Deadlock other ){
  7. Print ("entering checkOther ()");
  8. Try {Thread. sleep (2000 );}
  9. Catch (InterruptedException x ){}
  10. Print ("in checkOther ()-about to" + "invoke 'other. action ()'");
  11. // Call the action Method of the other object. Because this method is a synchronous method, it will try to obtain the object lock of the other object.
  12. Other. action ();
  13. Print ("leaving checkOther ()");
  14. }
  15. Public synchronized void action (){
  16. Print ("entering action ()");
  17. Try {Thread. sleep (500 );}
  18. Catch (InterruptedException x ){}
  19. Print ("leaving action ()");
  20. }
  21. Public void print (String msg ){
  22. ThreadPrint ("objID =" + objID + "-" + msg );
  23. }
  24. Public static void threadPrint (String msg ){
  25. String threadName = Thread. currentThread (). getName ();
  26. System. out. println (threadName + ":" + msg );
  27. }
  28. Public static void main (String [] args ){
  29. Final Deadlock obj1 = new Deadlock ("obj1 ");
  30. Final Deadlock obj2 = new Deadlock ("obj2 ");
  31. Runnable runA = new Runnable (){
  32. Public void run (){
  33. Obj1.checkOther (obj2 );
  34. }
  35. };
  36. Thread threadA = new Thread (runA, "threadA ");
  37. ThreadA. start ();
  38. Try {Thread. sleep (200 );}
  39. Catch (InterruptedException x ){}
  40. Runnable runB = new Runnable (){
  41. Public void run (){
  42. Obj2.checkOther (obj1 );
  43. }
  44. };
  45. Thread threadB = new Thread (runB, "threadB ");
  46. ThreadB. start ();
  47. Try {Thread. sleep (5000 );}
  48. Catch (InterruptedException x ){}
  49. ThreadPrint ("finished sleeping ");
  50. ThreadPrint ("about to interrupt () threadA ");
  51. ThreadA. interrupt ();
  52. Try {Thread. sleep (1000 );}
  53. Catch (InterruptedException x ){}
  54. ThreadPrint ("about to interrupt () threadB ");
  55. ThreadB. interrupt ();
  56. Try {Thread. sleep (1000 );}
  57. Catch (InterruptedException x ){}
  58. ThreadPrint ("did that break the deadlock? ");
  59. }
  60. }

The running result is as follows:


As shown in the result. action (), because both threads are trying to obtain the lock of the other side, but neither of them has released its own lock, a deadlock occurs and two threads are trying to interrupt in the main thread, but none.


Most of the Code is not prone to deadlocks. Deadlocks may hide for a long time in the code, waiting for uncommon conditions to occur, but even if it is a small probability, once a deadlock occurs, this can cause devastating damage. It is difficult to avoid deadlocks. The following principles help avoid deadlocks:

1. Only hold the lock within the shortest time required. Use the synchronous statement block instead of the entire synchronization method;

2. Try to write code that requires multiple locks at different times. If unavoidable, make sure that the thread holds the second lock for as short as possible;

3. Create and use a large lock to replace several small locks, and use the lock for mutual exclusion instead of the object-Level Lock of a single object;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.