Turn: "Java concurrent programming" nine: Deadlock (with code)

Source: Internet
Author: User

Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17200937


When a thread needs to hold multiple locks at the same time, it is possible to generate a deadlock. Consider the following scenario:

Thread A currently holds the mutex lock lock1, and thread B currently holds the mutex Lock2. Next, when thread a still holds lock1, it tries to get Lock2 because thread B is holding lock2, so thread a blocks waiting for thread B to release the Lock2. If thread B is trying to get lock1 when it holds lock2, because thread A is holding lock1, thread B blocks waiting for a to lock1 release. Both are waiting for the release of the lock held by each other, and neither of them has released the locks held by them, and the two will continue to clog up. This situation is called a deadlock.

Here is an example of a deadlock between two threads, as follows:

[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 the method is a synchronous method, and therefore attempts 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 this break the deadlock?");
  59. }
  60. }


The results of the operation are as follows:


As can be seen from the results, when executed to Other.action (), because two threads are trying to acquire the other's lock, but the other party did not release their locks, resulting in a deadlock, in the main thread to try to break two threads, but none of the results.


Most of the code is not prone to deadlocks, and deadlocks can be hidden in code for quite a long time, waiting for uncommon conditions to occur, but even a small probability can cause devastating damage if it happens. Avoiding deadlocks is a difficult thing to do, follow these guidelines to help avoid deadlocks:

1, only in the shortest time necessary to hold the lock, consider the use of synchronous statement block instead of the entire synchronization method;

2. Try to write code that does not need to hold multiple locks at the same time, and if unavoidable, make sure the thread holds the second lock for as short a time as possible;

3, create and use a large lock to replace a number of small locks, and the lock for mutual exclusion, rather than as an object-level lock for a single object;

Turn: "Java concurrent programming" nine: Deadlock (with code)

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.