The same time that developers use concurrency to improve performance in an app. Developers also need to be aware that threads can clog each other.
When the entire application is running slower than expected, the application does not run as expected running time. In this chapter. We need to carefully analyze the active problem that may affect the application of multithreading.
Dead lock
The concept of deadlocks is well known among software developers, and even ordinary computer users often use this concept. Although not used in the right situation. Strictly speaking, a deadlock means that two or more other threads are waiting for a thread to release its locked resources, while the thread requesting the resource also locks the resource requested by the other thread.
For example, the following:
1for2for resource A
For a better understanding of the problem, take a look at the following code:
Public classDeadlock implements Runnable {Private Static FinalObject Resource1 =NewObject ();Private Static FinalObject Resource2 =NewObject ();Private FinalRandom random =NewRandom (System.currenttimemillis ()); Public Static voidMain (string[] args) {Thread myThread1 =NewThread (NewDeadlock (),"Thread-1"); Thread myThread2 =NewThread (NewDeadlock (),"Thread-2"); Mythread1.start (); Mythread2.start (); } Public voidRun () { for(inti =0; I <10000; i++) {Boolean b = Random.nextboolean ();if(b) {System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Trying to lock resource 1. ");synchronized(Resource1) {System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Locked resource 1. "); System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Trying to lock resource 2. ");synchronized(RESOURCE2) {System. out. println ("["+ Thread. CurrentThread (). GetName () +"] Locked resource 2. "); } } }Else{System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Trying to lock resource 2. ");synchronized(RESOURCE2) {System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Locked resource 2. "); System. out. println ("["+ Thread.CurrentThread (). GetName () +"] Trying to lock resource 1. ");synchronized(Resource1) {System. out. println ("["+ Thread. CurrentThread (). GetName () +"] Locked resource 1. "); } } } } }}
As you can see from the code above. Two threads are started separately, and an attempt is being held to lock 2 static resources. But for deadlocks. We need two threads to lock resources in a different order, so we use random instances to select the resources that the thread wants to lock first.
If the Boolean variable b is, it is true resource1 locked. Then try to get resource2 the lock.
Suppose b it is false . The thread locks first resource2 , but attempts to lock resource1 . The program will encounter a deadlock problem in a moment, and then it will hang. The JVM will not end until we have finished:
[Thread-1] Trying toLockResource1.[thread-1] Locked Resource1.[thread-1] Trying to LockResource2.[thread-1] Locked Resource2.[thread-2] Trying to LockResource1.[thread-2] Locked Resource1.[thread-1] Trying to LockResource2.[thread-1] Locked Resource2.[thread-2] Trying to LockResource2.[thread-1] Trying to LockResource1.
In the above run, hold the lock, wait for the lock, thread-1 resource2 while the thread holds the lock resource1 thread-2 resource1 and waits resource2 for the lock.
Suppose we set b the value of the configuration true or false , it will not hit the deadlock. Because the order of operations is always consistent, the order in which the thread-1 thread-2 locks are requested is always consistent. Two threads will request a lock in the same order. Then a maximum of one thread will be temporarily blocked and can finally be run sequentially.
As a general result, the following conditions are required for the deadlock:
- Mutual exclusion : there must be a resource at some point that can only be visited by one thread.
- Resource hold : When a resource is locked. The thread still needs to get a lock on another resource.
- no preemption policy : When a thread has held a resource for some time. There is no mechanism for seizing threads to lock resources.
- loop Wait : There must be two or many other threads at run time. Ask each other for a locked resource.
Although the conditions that create deadlocks appear to be more, there is a common deadlock in multithreaded applications.
Developers can avoid deadlocks by breaking the necessary conditions for deadlocks, such as the following:
- Mutual exclusion: This requirement is usually unavoidable. There are very many times when resources really can only repel each other. But that's not always the case.
When using a DBMS system, a similar optimistic lock may be used to replace the original pessimistic locking mechanism (locking a row in the table when updating the data).
- There is also a viable option to handle resource holding when a lock on a resource is acquired. Get locks on other required resources immediately. Assume that the acquisition of the lock failed. Release all of the previously mutually exclusive resources.
Of course, such a way is not always possible. Resources that are likely to be locked before they are unknown or obsolete.
- One way to prevent deadlocks is to configure the last time-out for lock acquisition, assuming the lock is not immediately available. A
ReentrantLock Similar timeout method is provided in the SDK class.
- From the code above, we can see that the order of locking resources for each thread is the same, and no deadlock is generated. This process can be done by abstracting all of the request lock code into a single method. It is then called by the thread to implement it. This can effectively avoid deadlocks.
In a more advanced application, developers may need to consider implementing a system that detects deadlocks.
In this system, to implement some thread-based monitoring, when the future to acquire a lock. And try to ask for another lock. Log is logged. Assume that a graph is formed with threads and locks. Developers are able to detect 2 different threads that hold resources and request additional blocked resources at the same time. Suppose the developer can detect. And be able to force the blocked thread to release the resources that have been acquired, it is able to detect the deadlock on its own initiative and actively repair the deadlock problem.
Hunger
The thread scheduler determines the order in which the RUNNABLE threads in the state will run. Decisions are usually thread-based, so low-priority threads get less CPU time, and high-priority threads get more CPU time. Of course, such a dispatch sounds more reasonable. But sometimes it can cause problems. Assuming that a high-priority thread is always running, the low-priority thread will not be able to get enough time to run and be in a state of starvation.
So. It is recommended that developers configure thread priority only when it is really necessary.
An example of a very complex thread of starvation is the finalize() method. This feature in the Java language can be used for garbage collection. But when the developer looks finalizer at the priority of the thread. You will find that the priority of the operation is not the highest. Therefore, it is very likely that the finalize() method will run longer than other methods.
There is also a running time problem. The order in which threads are passed through the synchronization code block is undefined.
When very many parallel threads are required to pass through the encapsulated synchronous code block, the threads will wait longer than other threads to enter the synchronization code faster. In theory, they may never be able to enter blocks of code. This problem can be solved by using a fair locking scheme.
A fair lock takes into account the thread's wait time when selecting the next thread. The realization of a fair lock is java.util.concurrent.locks.ReentrantLock :
Assume ReentrantLock that the following constructors are used, for example:
/** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ publicReentrantLock(boolean fair) { newnew NonfairSync(); }
Incoming true , then ReentrantLock a fair lock, which will allow the thread to get the lock run in the order in which it was suspended.
This can reduce the hunger of threads, but it does not completely solve the problem of hunger, after all, the scheduling of the thread is operated by the operating system. So. ReentrantLockclass simply considers the thread that waits for the lock, and the dispatch does not work. Give me a sample example. Although a fair lock is used, the operating system gives low-priority threads a very short run time.
Java Threading and Multithreading (15)--Thread activity