Home > Java > javaTutorial > How to implement Java distributed lock

How to implement Java distributed lock

王林
Release: 2023-04-25 18:19:07
forward
1834 people have browsed it

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
Copy after login

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);
Copy after login

总的来说就是使用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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template