Introduction to distributed locks

Source: Internet
Author: User

[Switch] talking about distributed locks

Preface

With the continuous development of Internet technology, increasing data volumes, and increasingly complex business logic, traditional centralized systems cannot meet our business needs, distributed Systems are applied in more scenarios, and access to shared resources in distributed systems requires a mutex mechanism to prevent mutual interference between them to ensure consistency, in this case, we need to use distributed locks.

 

Distributed consistency

First, let's look at a small example:

Assume that A mall has 10 items in stock, user A wants to buy 6 items, and user B wants to buy 5 items. Ideally, user A has bought 6 items first, there are 6 fewer inventory items and 4 more. At this time, user B should not be able to buy 5 items, giving a prompt of insufficient quantity. In actual situations, users A and B get 10 items at the same time, and A buys 6 items. Before A updates the inventory, B buys 5 more items. At this time, B updates the inventory, five items are left, which is a typical e-commerce "seckilling" activity.

From the above example, it is not difficult to see that in the case of high concurrency, if not processed, There will be various unpredictable consequences. In this case of high concurrency and multithreading, the most effective and common way to solve the problem is to add a lock to the shared resources or operations on the shared resources to ensure that the access to the resources is mutually exclusive. The Java JDK has provided us with such a lock. You can use ReentrantLcok or synchronized to achieve mutually exclusive resource access. However, in distributed systems, due to the distribution of distributed systems, that is, multithreading and multi-process distribution in different machines, these two locks will lose the effect of the original locks, we need to implement distributed locks ourselves-distributed locks.

 

What are the requirements for Distributed locks?

1. better performance in obtaining and Releasing locks

2. Determine whether to obtain the lock must be atomic. Otherwise, multiple requests may obtain the lock.

3. When the network is interrupted or the machine is down and the lock cannot be released, the lock must be clear; otherwise, a deadlock will occur.

4. you can re-import a thread to obtain the same lock Multiple times. For example, if a thread executes a locking method, this method calls another method that requires the same lock, the thread can directly execute the called method without re-obtaining the lock;

5. blocking lock and non-blocking lock. If the lock is not obtained, the system continues to wait for the lock to be obtained. If the lock is not obtained, the system directly returns the lock failure.

 

Distributed Lock Implementation Method

I. Database locks

1. MySQL-based lock table

This implementation method relies entirely on the unique index of the database. When a lock is obtained, a record is inserted into the database, and the record is deleted when the lock is released. This method has the following problems:

(1) The lock has no expiration time. The unlock failure will lead to a deadlock. Other threads cannot obtain the lock any more, because the unique Index insert will return a failure.

(2) It can only be a non-blocking lock. If the insert operation fails, an error is reported and the queue cannot be entered for retry.

(3) The same thread cannot obtain the lock before releasing the lock.

2. Use optimistic locks to add version numbers

Check whether other threads have updated the update based on the version number. If the update is performed, the lock fails to be obtained.

II,Cache lock

Here we mainly introduce several distributed locks Based on redis:

1. implemented based on the setnx and expire commands

Based on the setnx (set if not exist) feature, when the key in the cache does not exist, it will go to set; otherwise, false will be returned directly. If true is returned, the lock is obtained. Otherwise, the lock fails to be obtained. To prevent deadlocks, we use the expire command to set a timeout value for the key to avoid this. However, this seems perfect, but it is actually flawed. When we set NX successfully, the thread is interrupted abnormally, and expire has not been set yet, a deadlock will occur.

There are two solutions to solve the above problems

The first type is the set version later than redis2.6.12, which provides a series of options

  • EX seconds-set the key expiration time, in seconds

  • PX milliseconds-set the key expiration time, in milliseconds

  • NX-the key value is set only when the key does not exist.

  • XX-the key value is set only when the key exists.

The second method uses setnx (), get (), and getset (). The general implementation process is as follows:

(1) The Asetnx thread has a timeout timestamp (t1). If true is returned, the lock is obtained.

(2) thread B uses the get command to obtain t1, Which is compared with the current timestamp to determine whether the request has timed out. If the request has timed out, the execution of step 3

(3) Calculate the new timeout time t2, and use the getset command to return t3 (this value may have been modified by other threads). If t1 = t3, the lock is obtained. If t1! = T3 indicates that the lock is obtained by other threads.

(4) After obtaining the lock, process the business logic and determine whether the lock has timed out. If the lock has not timed out, delete the lock. If the lock has timed out, skip this step (to prevent the lock from being deleted from other threads)

2. RedLock Algorithm

The redlock algorithm is a Distributed Lock implementation method recommended by redis authors. The algorithm content is as follows:

(1) obtain the current time;

(2) try to obtain the lock from five independent redis clients;

(3) Calculate the time consumed to obtain all locks. if and only when the client obtains the lock from most nodes and the time used to obtain the lock is less than the lock's valid time, it is deemed that the lock is obtained;

(4) recalculate the validity period. The original validity period minus the time consumed to obtain the lock;

(5) delete all instance locks

The redlock algorithm is more reliable than a single-node redis lock, but the conditions are harsh.

(1) Five nodes must be deployed to make Redlock more reliable.

(2) The lock can be obtained only when five nodes are requested. In the Future mode, requests are sent to five nodes concurrently and then the response results are obtained together, which can shorten the response time, however, it takes more time than a single-node redis lock.

Then, because more than three of the five nodes must be obtained, a lock conflict may occur, that is, everyone has obtained 1-2 locks, and no one can obtain the lock as a result, the author of redis draws on the raft algorithm to greatly reduce the conflict time by starting at the random time after the conflict, but this problem cannot be avoided very well, especially when obtaining the lock for the first time, therefore, the time cost for obtaining the lock increases.

If there are two down nodes on the five nodes, the availability of the lock will be greatly reduced. First, you must wait for the results of the two down nodes to time out before returning. In addition, there are only three nodes, the client must obtain the locks of all three nodes to possess the locks, which is more difficult.

If a network partition occurs, the client may never be able to obtain the lock. In this case, let's look at a more reliable distributed lock zookeeper lock.

 

Zookeeper Distributed Lock

First, let's take a look at the features of zookeeper and see why it is suitable for Distributed locks,

Zookeeper is a software that provides consistency services for distributed applications. It is a hierarchical file system directory tree structure. It specifies that a unified directory can have only one unique file name.

Data Model:

  • Permanent node: After a node is created, it does not disappear due to session failure.

  • Temporary node: opposite to a permanent node. If the client connection fails, delete the node immediately.

  • Ordered nodes: similar to the preceding two node features, If you specify to create such nodes, zk automatically adds a digital suffix after the node name and is ordered.

Monitor (watcher ):

  • When creating a node, you can register a monitor for the node. When the node status changes and watch is triggered, ZooKeeper will send only one notification to the client, because watch can only be triggered once.

Based on these features of zookeeper, let's look at how to use these features to implement distributed locks:

1. Create a lock directory lock

2. Thread A, who wants to obtain the lock, creates A temporary sequence node in the lock directory.

3. obtain all the sub-nodes in the lock directory, and then obtain the sibling nodes smaller than themselves. If they do not exist, it means that the current thread has the smallest sequence number and the lock is obtained.

4. thread B obtains all nodes, determines that it is not the smallest node, and sets the listener (watcher) nodes smaller than their own times (only focus on nodes smaller than their own times to prevent "Herd Effect ")

5. After thread A finishes processing, it deletes its own node. Thread B listens to the change event, determines that it is the smallest node, and obtains the lock.

 

Summary

In a distributed system, shared resources are commonly used for mutual access. A common solution is to use distributed locks to access shared resources, here we only introduce several common distributed locks. There are many implementation methods for Distributed locks. Select the appropriate distributed locks based on the business and compare the above several locks:

Database lock:

  • Advantage: direct use of the database is easy to use.

  • Disadvantage: Most Bottlenecks of distributed systems are in databases. Using Database locks will increase the burden on databases.

Cache lock:

  • Advantage: high performance makes it easy to implement. When occasional lock failures are allowed, the normal use of the system is not affected. cache locks are recommended.

  • Disadvantage: the lock timeout mechanism is not very reliable. When the thread acquires the lock, the lock times out because of a long processing time.

Zookeeper lock:

  • Advantages: release locks without timeout; high reliability; zookeeper locks are recommended when the system requires high reliability.

  • Disadvantage: the performance is inferior to the cache lock because you need to frequently create and delete nodes.

 

Reprinted Please note: "This article is reposted from keeper.com (text/Zhang songran )"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.