What is Distributed Lock
Baidu itself. . .
Why Distributed Lock
Distributed Lock technology selection
File system
Process
From a specified location to determine whether there lock.txt, does not exist, create (that is, means that the current thread to acquire the lock), delete lock.txt after the execution; it is created when there is unsuccessful (circulated to wait until you have created success ).
problem
Once created lock.txt t1, the sudden interruption cause problems, it will not be lock.txt t1 (thread that created it) removed. This will lead to lock.txt has always existed, t2 been circulating, that there has been a deadlock.
database
Its processes with a similar file system, are created after the lock because the creator of the sudden interruption caused by the lock can not be released.
Cache
After using the cache as a distributed lock, than the previous two programs mentioned prominent advantage is that you can set a lock expiration time, which means that even if a deadlock occurs, it is only a short time, waiting deadlock expired, other threads you can continue to compete.
Zookeeper
Why Zookeeper is most suitable as a distributed lock, first understand some of the characteristics of Zookeeper.
Temporary focus on that node:
Temporary survival depends on the client node session, when the session ends, the temporary node will be automatically deleted (of course, you can also manually delete the temporary node).
This means that when connected to multiple clients Zookeeper, if a client disconnects, then it creates a temporary node will be automatically deleted.
It explains how to get the lock is released, then the next is to explain how to compete lock.
When the process has not yet released the lock to get 1, 2 process to lock (node) registered an event listener, when the lock is removed, listening to events triggered, so as to awaken the process 2 continues to snatch lock.