Table of Contents
1. Introduction to distributed locks
2. Implementing distributed locks based on Redis
1. How to implement the simplest distributed lock based on Redis
2. Why set an expiration time for the lock
3. How to achieve graceful renewal of the lock
4. 如何实现可重入锁
Home Java javaTutorial How to implement Java distributed lock

How to implement Java distributed lock

Apr 25, 2023 pm 06:19 PM
java

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

How to implement Java distributed lock

# 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.

How to implement Java distributed lock

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. SETNXThat 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

How to implement Java distributed lock

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.

How to implement Java distributed lock

使用方式举例:

// 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles