search
HomeJavajavaTutorialSample code sharing on how to avoid deadlock in Java

Sample code sharing on how to avoid deadlock in Java

Jun 18, 2017 am 09:48 AM
javahowdeadlockExampleavoid

Deadlock can be avoided in some cases. This article will demonstrate three techniques for avoiding deadlocks. Friends who are interested in knowledge about avoiding deadlocks in Java should learn from this article

In some cases, deadlocks can be avoided. This article will demonstrate three techniques for avoiding deadlock:

1. Locking sequence

2. Locking time limit

3. Deadlock detection

Lock order

When multiple threads require the same locks but lock them in different orders, deadlock can easily occur.

If we can ensure that all threads obtain locks in the same order, deadlock will not occur. Look at the following example:


Thread 1:
 lock A 
 lock B
Thread 2:
  wait for A
  lock C (when A locked)
Thread 3:
  wait for A
  wait for B
  wait for C

If a thread (such as thread 3) needs some locks, then it must acquire the locks in a determined order. It can only acquire subsequent locks after acquiring the lock in front of it in sequence.

For example, thread 2 and thread 3 can only try to acquire lock C after acquiring lock A (acquiring lock A is a necessary condition for acquiring lock C). Because thread 1 already owns lock A, threads 2 and 3 need to wait until lock A is released. Then they must successfully lock A before they try to lock B or C.

Locking in order is an effective deadlock prevention mechanism. However, this method requires you to know all the locks that may be used in advance (and properly sequence these locks), but sometimes it is unpredictable.

Lock time limit

Another way to avoid deadlock is to add a timeout when trying to acquire the lock. This means that if this time limit is exceeded during the process of trying to acquire the lock, the thread will give up the lock request. If a thread does not successfully acquire all required locks within a given time limit, it will roll back and release all acquired locks, then wait for a random period of time before trying again. This random waiting time gives other threads the opportunity to try to acquire the same locks, and allows the application to continue running without acquiring the lock (you can continue to run and do other things after the lock times out) , then go back and repeat the previous locking logic).
The following is an example showing a scenario where two threads try to acquire the same two locks in different orders, and then roll back and try again after a timeout occurs:


 Thread 1 locks A
Thread 2 locks B
Thread 1 attempts to lock B but is blocked
Thread 2 attempts to lock A but is blocked
Thread 1's lock attempt on B times out
Thread 1 backs up and releases A as well
Thread 1 waits randomly (e.g. 257 millis) before retrying.
Thread 2's lock attempt on A times out
Thread 2 backs up and releases B as well
Thread 2 waits randomly (e.g. 43 millis) before retrying.

In the above example, thread 2 retries the lock 200 milliseconds earlier than thread 1, so it can successfully acquire two locks first. At this time, thread 1 tries to acquire lock A and is in the waiting state. When thread 2 ends, thread 1 can also successfully acquire these two locks (unless thread 2 or other threads acquire some of the locks before thread 1 successfully acquires the two locks).

It should be noted that due to the lock timeout, we cannot think that this scenario must be a deadlock. It could also be that the thread that acquired the lock (causing other threads to timeout) takes a long time to complete its task.

In addition, if there are many threads competing for the same batch of resources at the same time, even if there is a timeout and rollback mechanism, it may still cause these threads to try repeatedly but never get the lock. If there are only two threads and the retry timeout is set between 0 and 500 milliseconds, this phenomenon may not happen, but if there are 10 or 20 threads, the situation is different. Because the probability that these threads will wait for equal retry times is much higher (or so close that it will cause problems). (The timeout and retry mechanism is to avoid competition that occurs at the same time. However, when there are many threads, there is a high possibility that the timeout time of two or more threads will be the same or close, so even if competition occurs and a timeout occurs, Later, because the timeout is the same, they will start to retry at the same time, resulting in a new round of competition and bringing new problems)

There is a problem with this mechanism, which cannot be done in Java. Set the timeout period for synchronized synchronized blocks. You need to create a custom lock, or use the tools in the java.util.concurrent package in Java 5. Writing a custom lock class is not complicated, but is beyond the scope of this article.

Deadlock detection

Deadlock detection is a better deadlock prevention mechanism. It is mainly aimed at those situations where it is impossible to achieve sequential Scenarios where locking and lock timeout are not feasible.

Whenever a thread acquires a lock, it will be recorded in the thread- and lock-related data structures (map, graph, etc.). In addition, whenever a thread requests a lock, it also needs to be recorded in this data structure.

When a thread fails to request a lock, the thread can traverse the lock relationship graph to see if a deadlock occurs. For example, thread A requests lock 7, but lock 7 is held by thread B at this time. At this time, thread A can check whether thread B has requested the lock currently held by thread A. If thread B does have such a request, then a deadlock has occurred (thread A owns lock 1 and requests lock 7; thread B owns lock 7 and requests lock 1).

Of course, deadlock is generally more complicated than the situation where two threads hold each other's locks. Thread A waits for thread B, thread B waits for thread C, thread C waits for thread D, and thread D waits for thread A. In order for thread A to detect deadlock, it needs to progressively detect all locks requested by B. Starting from the lock requested by thread B, thread A found thread C, then found thread D, and found that the lock requested by thread D was held by thread A itself. This is when it knows a deadlock has occurred.
So what should these threads do when a deadlock is detected?

A feasible approach is to release all locks, roll back, and wait for a random period of time before trying again. This is similar to a simple lock timeout. The difference is that the rollback occurs only when a deadlock has occurred, not because the lock request has timed out. Although there is backoff and waiting, if there are a large number of threads competing for the same batch of locks, they will still deadlock repeatedly.

A better solution is to set priority for these threads, let one (or several) threads roll back, and the remaining threads continue as if no deadlock has occurred. They need locks. If the priorities assigned to these threads are fixed, the same threads will always have a higher priority. To avoid this problem, random priorities can be set when a deadlock occurs.

The above is the detailed content of Sample code sharing on how to avoid deadlock in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!