Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of deadlock dead lock in java

2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

The example analysis of deadlock dead lock in java, aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Brief introduction

In order to ensure the security of shared data in java, we introduce the lock mechanism. With a lock, a deadlock may occur.

The reason for deadlock is that multiple threads lock the resources needed by each other, and then the existing resources are not released, resulting in a loop waiting.

Generally speaking, deadlocks are likely to occur if different threads do not agree on the order of locking and releasing locks.

Different locking order

Let's look at an example of a different locking order:

Public class DiffLockOrder {private int amount;public DiffLockOrder (int amount) {this.amount=amount;} public void transfer (DiffLockOrder target,int transferAmount) {synchronized (this) {synchronized (target) {if (amount)

< transferAmount){ System.out.println("余额不足!"); }else{ amount=amount-transferAmount; target.amount=target.amount+transferAmount; } } } }} 上面的例子中,我们模拟一个转账的过程,amount用来表示用户余额。transfer用来将当前账号的一部分金额转移到目标对象中。 为了保证在transfer的过程中,两个账户不被别人修改,我们使用了两个synchronized关键字,分别把transfer对象和目标对象进行锁定。 看起来好像没问题,但是我们没有考虑在调用的过程中,transfer的顺序是可以发送变化的: DiffLockOrder account1 = new DiffLockOrder(1000); DiffLockOrder account2 = new DiffLockOrder(500); Runnable target1= ()->

Account1.transfer (account2200); Runnable target2= ()-> account2.transfer (account1100); new Thread (target1). Start (); new Thread (target2). Start ()

In the above example, we define two account, and then the two accounts transfer money to each other, which is likely to lead to mutual locking and deadlock.

Use private class variables

There is a problem with the order of using two sync, so is there any way to synchronize all instances with just one sync?

Yes, we can use the class variable of private, because the class variable is shared among all instances, so sync for once is enough:

Public class LockWithPrivateStatic {private int amount;private static final Object lock = new Object (); public LockWithPrivateStatic (int amount) {this.amount=amount;} public void transfer (LockWithPrivateStatic target, int transferAmount) {synchronized (lock) {if (amount < transferAmount) {System.out.println ("insufficient balance!") ;} else {amount = amount-transferAmount; target.amount = target.amount + transferAmount;} uses the same Order

The reason why we have a deadlock is that we can't control the order of locking. If we can control the order of locking, will there be no deadlock?

With this in mind, we add an id field to the object:

Private final long id; / / unique ID to sort private static final AtomicLong nextID = new AtomicLong (0); / / to generate IDpublic DiffLockWithOrder (int amount) {this.amount=amount;this.id = nextID.getAndIncrement ();}

When initializing objects, we use static's AtomicLong class to generate a unique ID for each object.

When doing transfer, we first compare the ID sizes of the two objects, then sort them according to ID, and finally lock them in the installation order. In this way, the order can be guaranteed, thus avoiding deadlocks.

Public void transfer (DiffLockWithOrder target, int transferAmount) {DiffLockWithOrder fist, second;if (compareTo (target) < 0) {fist = this; second = target;} else {fist = target; second = this;} synchronized (fist) {synchronized (second) {if (amount < transferAmount) {System.out.println ("insufficient balance!") ;} else {amount=amount-transferAmount; target.amount=target.amount+transferAmount;}} release the lock that is already occupied

A deadlock is a lock occupied by each other, but the lock of the other party has not been released. Let's consider whether automatically releasing the occupied lock can also solve the problem of deadlock if the lock cannot be obtained.

Because ReentrantLock has a tryLock () method, we can use this method to determine whether the lock can be acquired or not, and then release the occupied lock.

We use ReentrantLock to complete this example:

Public class DiffLockWithReentrantLock {private int amount;private final Lock lock = new ReentrantLock (); public DiffLockWithReentrantLock (int amount) {this.amount=amount;} private void transfer (DiffLockWithReentrantLock target, int transferAmount) throws InterruptedException {while (true) {if (this.lock.tryLock ()) {try {if (target.lock.tryLock ()) {try {if (amount < transferAmount) {System.out.println ("insufficient balance!") ;} else {amount=amount-transferAmount; target.amount=target.amount+transferAmount;} break;} finally {target.lock.unlock () } finally {this.lock.unlock ();}} / / Random sleep for a certain period of time to ensure that the lock Thread.sleep (1000+new Random (1000L) .nextInt (1000)) can be released;}

We put two tryLock methods in the while loop and iterate through the loop if we can't get the lock.

This is the answer to the sample analysis question of deadlock dead lock in java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report