Java multithreading deadlock and resource limitations detailed __java

Source: Internet
Author: User

The lock is a very useful tool, with a lot of scenes, because it's very simple to use and easy to understand. But at the same time it also brings some trouble, that is, may cause deadlock, once the deadlock, it will cause system function is not available. The concept of deadlock

What is a dead lock? The so-called deadlock: refers to two or more than two processes in the implementation process, because of competitive resources or due to the communication between each other caused by a blocking phenomenon, without external forces, they will not be able to push down. It is said that the system is in a deadlock state or the system produces a deadlock, and these processes that are always waiting for each other are called deadlock processes. the necessary conditions for deadlock generation

1 Mutually exclusive conditions: refers to the process of allocating resources to the exclusive use, that is, for a period of time a resource is only occupied by a process. If there are other processes requesting resources at this time, the requester can only wait until the process that occupies the resource is released.
2 Request and retention conditions: The process has maintained at least one resource, but a new resource request has been made, and the resource has been occupied by other processes, at which point the request process is blocked, but the other resources that it has obtained remain in place.
( 3) No deprivation of condition: The resources that the process has obtained, which cannot be deprived until it has been used, can only be released by itself when the use is complete.
4 loop waiting condition: refers to the deadlock, there must be a process-the chain of resources, that is, the process set {p0,p1,p2,,pn} in the P0 is waiting for a P1 occupied resources; P1 is waiting for P2 to occupy the resources, ..., PN is waiting for resources that have been P0 occupied. Deadlock Code Instance

public class Deadlockdemo {private static String a = "a";
    private static String B = "B";
    public static void Main (string[] args) {new Deadlockdemo (). Deadlock (); /** * Deadlock * @author Fuyuwei * May 13, 2017 afternoon 9:27:32 * * private void Deadlock () {Threa  d t1 = new Thread (new Runnable () {@SuppressWarnings ("static-access") @Override public void Run () {synchronized (A) {try {thread.currentthread ().
                    Sleep (2000);
                    catch (Interruptedexception e) {e.printstacktrace ();
                    } synchronized (B) {System.out.println ("1");
        }
                }
            }
        });  Thread t2 = new Thread (new Runnable () {@Override public void run () {synchronized (B) {syNchronized (A) {System.out.println ("2");
        }
                }
            }
        });
        T1.start ();
    T2.start (); }
}

Thread A sleeps after 2 seconds to lock B synchronous print 1, but then B has been locked by a second thread, and the second antenna locks a print 2, so that a waits for B but holds B, and B waits for a but holds a, and it creates a deadlock.
Of course this code is purely for the purpose of demonstrating deadlocks, and this code is largely not seen in practice. In the actual work of the thread may get a database lock, release the lock when thrown an exception, did not release.
Once a deadlock occurs, the business is perceptible because the service cannot be continued, and only the dump thread can be used to see exactly which thread is having a problem, and the threaded information tells us that it is a deadlock caused by lines 42nd and 31st of the Deadlockdemo class.

"Thread-2" prio=5 tid=7fc0458d1000 nid=0x116c1c000 waiting for monitor entry [116c1b000
java.lang.Thread.State: BLOCKED (on object monitor) in
Com.ifeve.book.forkjoin.deadlockdemo$2.run (deadlockdemo.java:42)
-Waiting to Lock <7fb2f3ec0> (a java.lang.String)
-locked <7fb2f3ef8> (a java.lang.String)
at Java.lang.Thread.run (thread.java:695)
"Thread-1" prio=5 tid=7fc0430f6800 nid=0x116b19000 waiting for Monitor Entry [116b18000
Java.lang.Thread.State:BLOCKED (on object monitor) at
Com.ifeve.book.forkjoin.DeadLockDemo $1.run (deadlockdemo.java:31)
-Waiting to lock <7fb2f3ef8> (a java.lang.String)
-locked <7FB2F3EC0 > (a java.lang.String) at
Java.lang.Thread.run (thread.j
ways to avoid deadlocks

1, to avoid a thread to acquire multiple locks at the same time.
2, to avoid a thread in the lock at the same time occupy multiple resources, as far as possible to ensure that each lock occupies only one resource.
3, try to use the timing lock, use Lock.trylock (timeout) to replace the use of internal locking mechanism.
4, for database locks, lock and unlock must be in a database connection, or there will be a failure to unlock the situation. what is a resource constraint

Resource restriction refers to the speed of execution of a program in the case of concurrent programming, which is limited by the computer hardware resources or software resources. For example, the server's bandwidth is only 2mb/s, the download speed of a resource is 1mb/s per second, the system starts 10 threads to download resources, download speed does not become 10mb/s, so in concurrent programming, consider the limitations of these resources. Hardware resources limit the bandwidth of the upload/download speed, hard disk read and write speed and CPU processing speed. Software resources limit the number of connections to the database and the number of socket connections. issues caused by resource constraints

In concurrent programming, the principle of speeding up code execution is to turn the serial execution part of code into concurrent execution, however, if the serial code is executed concurrently, because the resource is still serially executed, the program will not only speed up execution but also be slower because of the increased time for context switching and resource scheduling. For example, before see a program using multithreading in the office network concurrent download and processing data, resulting in CPU utilization reached 100%, a few hours can not run to complete the task, and then modified into a single thread, one hours on the implementation completed. how to resolve resource constraints

For hardware resource constraints, you might consider using a clustered parallel execution program. Since a stand-alone resources limited system, then let the program run on multiple machines. For example, use ODPs, Hadoop, or build your own server cluster, and different machines handle different data. You can calculate a machine number by using the number of data id% machines, and then process the data by the corresponding numbered machine. For software resource constraints, consider using a pool of resources to reuse resources. For example, use a connection pool to reuse a database and socket connection, or create only one connection when you call the other WebService interface to get the data. concurrent programming in the context of resource constraints

How to make a program run faster with resource constraints. The approach is to adjust the concurrency of the program according to different resources, such as downloading a file program that relies on two resources-bandwidth and hard drive read and write speed. When there is a database operation, the number of database connections is involved, and if the SQL statement executes very quickly and the number of threads is much larger than the number of database connections, some threads are blocked waiting for the database to connect.

Related Article

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.