How to solve problems when using polling locks in Java?
Problem Demonstration
When we do not use polling locks, this problem may occur:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class DeadLockByReentrantLock { public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1 Thread t1 = new Thread(new Runnable() { @Override public void run() { lockA.lock(); // 加锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(1000); System.out.println("线程 1:等待获取 B..."); lockB.lock(); // 加锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockA.unlock(); // 释放锁 } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 } } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { Thread.sleep(1000); System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockB.unlock(); // 释放锁 } } }); t2.start(); // 运行线程 } }
The execution results of the above code are as follows:
As can be seen from the above results, at this time, the program has threads waiting for each other and trying to obtain each other's (lock) resources. This is a typical situation. Deadlock problem.
Simple version of polling lock
When a deadlock problem occurs, we can use polling lock to solve it. Its implementation idea is to obtain multiple Lock, if any lock acquisition fails during the process, a rollback operation is performed, all locks owned by the current thread are released, and wait for the next re-execution. This can prevent multiple threads from owning and occupying the lock resources at the same time, thus directly solving the problem. For the problem of deadlock, the simple version of polling lock is implemented as follows:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SolveDeadLockExample2 { public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1(使用轮询锁) Thread t1 = new Thread(new Runnable() { @Override public void run() { // 调用轮询锁 pollingLock(lockA, lockB); } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { Thread.sleep(1000); System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockB.unlock(); // 释放锁 } } }); t2.start(); // 运行线程 } /** * 轮询锁 */ private static void pollingLock(Lock lockA, Lock lockB) { // 轮询锁 while (true) { if (lockA.tryLock()) { // 尝试获取锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(1000); System.out.println("线程 1:等待获取 B..."); if (lockB.tryLock()) { // 尝试获取锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockB.unlock(); // 释放锁 System.out.println("线程 1:释放锁 B."); break; } } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 System.out.println("线程 1:释放锁 A."); } } // 等待一秒再继续执行 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
The execution result of the above code is as follows:
It can be seen from the above results that when we use polling locks in the program, deadlock problems will not occur, but the above polling locks are not perfect. Let’s take a look at this What kind of problems will there be with polling locks?
Question 1: Infinite loop
For the above simple version of the polling lock, if a thread continues to occupy the lock resource or occupies the lock resource for a long time, it will cause the polling lock to enter In an infinite loop state, it will try to keep acquiring lock resources, which will cause new problems and unnecessary performance overhead. Specific examples are as follows.
Counterexample
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SolveDeadLockExample { public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1(使用轮询锁) Thread t1 = new Thread(new Runnable() { @Override public void run() { // 调用轮询锁 pollingLock(lockA, lockB); } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { Thread.sleep(1000); System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } catch (InterruptedException e) { e.printStackTrace(); } finally { // 如果此处代码未执行,线程 2 一直未释放锁资源 // lockB.unlock(); } } }); t2.start(); // 运行线程 } /** * 轮询锁 */ public static void pollingLock(Lock lockA, Lock lockB) { while (true) { if (lockA.tryLock()) { // 尝试获取锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(1000); System.out.println("线程 1:等待获取 B..."); if (lockB.tryLock()) { // 尝试获取锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockB.unlock(); // 释放锁 System.out.println("线程 1:释放锁 B."); break; } } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 System.out.println("线程 1:释放锁 A."); } } // 等待一秒再继续执行 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
The execution results of the above code are as follows:
As can be seen from the above results, the thread 1 The polling lock enters an infinite loop state.
Optimized version
In view of the above infinite loop situation, we can improve the following two ideas:
Add the maximum number of times limit: If the lock has not been obtained after n attempts to obtain the lock, it is considered that the lock acquisition failed, and the polling is terminated after the failure strategy is executed (the failure strategy can be logging or other operations) ;
Add the maximum duration limit: If the lock has not been obtained after n seconds of trying to obtain the lock, it is considered that the lock acquisition failed, and after the failure strategy is executed Terminate polling.
Any one of the above strategies can solve the problem of infinite loop. For the sake of implementation cost, we can use the maximum number of polls to improve the polling lock,
The specific implementation code is as follows:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SolveDeadLockExample { public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1(使用轮询锁) Thread t1 = new Thread(new Runnable() { @Override public void run() { // 调用轮询锁 pollingLock(lockA, lockB, 3); } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { Thread.sleep(1000); System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } catch (InterruptedException e) { e.printStackTrace(); } finally { // 线程 2 忘记释放锁资源 // lockB.unlock(); // 释放锁 } } }); t2.start(); // 运行线程 } /** * 轮询锁 * * maxCount:最大轮询次数 */ public static void pollingLock(Lock lockA, Lock lockB, int maxCount) { // 轮询次数计数器 int count = 0; while (true) { if (lockA.tryLock()) { // 尝试获取锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(1000); System.out.println("线程 1:等待获取 B..."); if (lockB.tryLock()) { // 尝试获取锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockB.unlock(); // 释放锁 System.out.println("线程 1:释放锁 B."); break; } } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 System.out.println("线程 1:释放锁 A."); } } // 判断是否已经超过最大次数限制 if (count++ > maxCount) { // 终止循环 System.out.println("轮询锁获取失败,记录日志或执行其他失败策略"); return; } // 等待一秒再继续尝试获取锁 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
The execution results of the above code are as follows:
It can be seen from the above results that after we improve it, the polling lock will not have the problem of infinite loop. It will terminate execution after trying a certain number of times.
Problem 2: Thread starvation
The polling waiting time of our above polling lock is a fixed time, as shown in the following code:
// 等待 1s 再尝试获取(轮询)锁 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
This will cause the problem of thread starvation under special circumstances, that is, the problem of polling locks never being able to obtain the lock, such as the following example.
Counterexample
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SolveDeadLockExample { public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1(使用轮询锁) Thread t1 = new Thread(new Runnable() { @Override public void run() { // 调用轮询锁 pollingLock(lockA, lockB, 3); } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { while (true) { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } finally { lockB.unlock(); // 释放锁 } // 等待一秒之后继续执行 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t2.start(); // 运行线程 } /** * 轮询锁 */ public static void pollingLock(Lock lockA, Lock lockB, int maxCount) { // 循环次数计数器 int count = 0; while (true) { if (lockA.tryLock()) { // 尝试获取锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(100); // 等待 0.1s(获取锁需要的时间) System.out.println("线程 1:等待获取 B..."); if (lockB.tryLock()) { // 尝试获取锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockB.unlock(); // 释放锁 System.out.println("线程 1:释放锁 B."); break; } } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 System.out.println("线程 1:释放锁 A."); } } // 判断是否已经超过最大次数限制 if (count++ > maxCount) { // 终止循环 System.out.println("轮询锁获取失败,记录日志或执行其他失败策略"); return; } // 等待一秒再继续尝试获取锁 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
The execution results of the above code are as follows:
As can be seen from the above results, the thread 1 (polling lock) has not successfully acquired the lock. The reason for this result is: Thread 1's waiting time for each poll is fixed 1s, and Thread 2 also has the same frequency, acquiring the lock every 1s, so This will cause thread 2 to always successfully acquire the lock first, while thread 1 will always be in a "starving" situation. The execution process is as shown in the figure below:
Optimized version
Next, we can improve the fixed waiting time of the polling lock to a fixed time random time method, so that we can avoid the problem of acquiring the lock. The frequency is consistent, which causes the problem of "starvation" of the polling lock. The specific implementation code is as follows:
import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SolveDeadLockExample { private static Random rdm = new Random(); public static void main(String[] args) { Lock lockA = new ReentrantLock(); // 创建锁 A Lock lockB = new ReentrantLock(); // 创建锁 B // 创建线程 1(使用轮询锁) Thread t1 = new Thread(new Runnable() { @Override public void run() { // 调用轮询锁 pollingLock(lockA, lockB, 3); } }); t1.start(); // 运行线程 // 创建线程 2 Thread t2 = new Thread(new Runnable() { @Override public void run() { while (true) { lockB.lock(); // 加锁 System.out.println("线程 2:获取到锁 B!"); try { System.out.println("线程 2:等待获取 A..."); lockA.lock(); // 加锁 try { System.out.println("线程 2:获取到锁 A!"); } finally { lockA.unlock(); // 释放锁 } } finally { lockB.unlock(); // 释放锁 } // 等待一秒之后继续执行 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t2.start(); // 运行线程 } /** * 轮询锁 */ public static void pollingLock(Lock lockA, Lock lockB, int maxCount) { // 循环次数计数器 int count = 0; while (true) { if (lockA.tryLock()) { // 尝试获取锁 System.out.println("线程 1:获取到锁 A!"); try { Thread.sleep(100); // 等待 0.1s(获取锁需要的时间) System.out.println("线程 1:等待获取 B..."); if (lockB.tryLock()) { // 尝试获取锁 try { System.out.println("线程 1:获取到锁 B!"); } finally { lockB.unlock(); // 释放锁 System.out.println("线程 1:释放锁 B."); break; } } } catch (InterruptedException e) { e.printStackTrace(); } finally { lockA.unlock(); // 释放锁 System.out.println("线程 1:释放锁 A."); } } // 判断是否已经超过最大次数限制 if (count++ > maxCount) { // 终止循环 System.out.println("轮询锁获取失败,记录日志或执行其他失败策略"); return; } // 等待一定时间(固定时间 + 随机时间)之后再继续尝试获取锁 try { Thread.sleep(300 + rdm.nextInt(8) * 100); // 固定时间 + 随机时间 } catch (InterruptedException e) { e.printStackTrace(); } } } }
The execution results of the above code are as follows:
The above is the detailed content of How to solve problems when using polling locks in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
