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.
1 2 3 4 5 6 |
|
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 自动续期机制。
1 2 |
|
总的来说就是使用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

AI Hentai Generator
Generate AI Hentai for free.

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



Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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
