In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "java deadlock example analysis". In daily operation, I believe many people have doubts about java deadlock example analysis. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "java deadlock example analysis". Next, please follow the editor to study!
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 ID public 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.
At this point, the study on "java deadlock example analysis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.