How to implement Java distributed lock
1. Introduction to distributed locks
Single machine multi-threading: In Java, we usually use local locks such as the ReetrantLock class and the synchronized keyword to control multiple threads in a JVM process to access local shared resources. Access
# Distributed systems: Different services/clients usually run on separate JVM processes. If multiple JVM processes share the same resource, there is no way to achieve mutually exclusive access to the resource using local locks. Thus, distributed locks were born.
For example: A total of 3 copies of the system's order service are deployed, all of which provide services to the outside world. Users need to check the inventory before placing an order. In order to prevent overselling, a lock is required to achieve synchronous access to the inventory check operation. Since the order service is located in a different JVM process, local locks will not work properly in this case. We need to use distributed locks, so that even if multiple threads are not in the same JVM process, they can obtain the same lock, thereby achieving mutually exclusive access to shared resources.
A most basic distributed lock needs to meet:
Mutual exclusion: at any time, the lock can only be held by one thread Hold;
Highly available: The lock service is highly available. Moreover, even if there is a problem with the client's code logic for releasing the lock, the lock will eventually be released and will not affect other threads' access to shared resources.
Reentrant: After a node acquires the lock, it can acquire the lock again.
2. Implementing distributed locks based on Redis
1. How to implement the simplest distributed lock based on Redis
Whether it is a local lock or The core of distributed locks lies in == "mutual exclusion" ==.
In Redis, the SETNX
command can help us achieve mutual exclusion. SETNX
That is, SET if Not eXists (corresponding to the setIfAbsent method in Java). If the key does not exist, the value of the key will be set. If key already exists, SETNX does nothing.
> SETNX lockKey uniqueValue
(integer) 1
> SETNX lockKey uniqueValue
(integer) 0
To release the lock, directly Delete the corresponding key through the DEL command
> DEL lockKey
(integer) 1
In order to prevent accidentally deleting other locks, we recommend here Use Lua script to judge by the value (unique value) corresponding to the key.
The Lua script is chosen to ensure the atomicity of the unlocking operation. Because Redis can execute Lua scripts in an atomic manner, thus ensuring the atomicity of the lock release operation.
// 释放锁时,先比较锁对应的 value 值是否相等,避免锁的误释放 if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end
This is the simplest Redis distributed lock implementation. The implementation method is relatively simple and the performance is very efficient. However, there are some problems with implementing distributed locking in this way. For example, if the application encounters some problems, such as the logic of releasing the lock suddenly hangs up, the lock may not be released, and the shared resources can no longer be accessed by other threads/processes.
2. Why set an expiration time for the lock
Mainly to prevent the lock from being released
127.0.0.1:6379> SET lockKey uniqueValue EX 3 NX
OK
lockKey: the lock name;
uniqueValue: a random string that can uniquely identify the lock;
NX: SET can only be successful when the key value corresponding to the lockKey does not exist;
EX: Expiration time setting (in seconds ) EX 3 indicates that this lock has an automatic expiration time of 3 seconds. Corresponding to EX is PX (in milliseconds), both of which are expiration time settings.
Be sure to ensure that setting the value and expiration time of the specified key is an atomic operation! ! ! Otherwise, there may still be a problem that the lock cannot be released.
This solution also has loopholes:
If the time to operate the shared resource is greater than the expiration time, there will be a problem of early expiration of the lock, which will lead to distributed locks Direct failure
If the lock timeout is set too long, it will affect performance
3. How to achieve graceful renewal of the lock
Redisson is an open source Java language Redis client that provides many out-of-the-box features, including not only the implementation of multiple distributed locks. Moreover, Redisson also supports multiple deployment architectures such as Redis stand-alone, Redis Sentinel, and Redis Cluster.
The distributed lock in Redisson comes with an automatic renewal mechanism. It is very simple to use and the principle is relatively simple. It provides a Watch Dog specially used to monitor and renew the lock. If the thread operating the shared resource has not completed its execution, Watch Dog will continuously extend the expiration time of the lock to ensure that the lock will not be released due to timeout.
使用方式举例:
// 1.获取指定的分布式锁对象
RLock lock = redisson.getLock("lock");
// 2.拿锁且不设置锁超时时间,具备 Watch Dog 自动续期机制
lock.lock();
// 3.执行业务
...
// 4.释放锁
lock.unlock();
只有未指定锁超时时间,才会使用到 Watch Dog 自动续期机制。
// 手动给锁设置过期时间,不具备 Watch Dog 自动续期机制 lock.lock(10, TimeUnit.SECONDS);
总的来说就是使用Redisson,它带有自动的续期机制
4. 如何实现可重入锁
所谓可重入锁指的是在一个线程中可以多次获取同一把锁,比如一个线程在执行一个带锁的方法,该方法中又调用了另一个需要相同锁的方法,则该线程可以直接执行调用的方法即可重入 ,而无需重新获得锁。像 Java 中的 synchronized 和 ReentrantLock 都属于可重入锁。
可重入分布式锁的实现核心思路是线程在获取锁的时候判断是否为自己的锁,如果是的话,就不用再重新获取了。为此,我们可以为每个锁关联一个可重入计数器和一个占有它的线程。当可重入计数器大于 0 时,则锁被占有,需要判断占有该锁的线程和请求获取锁的线程是否为同一个。
The above is the detailed content of How to implement Java distributed lock. 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.
