zookeeper--Implementing Distributed Lock

1: Multithreading

The characteristic of java language is multithreading, of course, there will be corresponding challenges under the advantages. In multithreading environment, thread security becomes a problem that developers must avoid. When a thread shares a variable, according to the memory model, each thread has its own local memory, and the shared variable is stored in the main memory. In memory. Of course, if it is read, it certainly will not cause thread safety problems. Now when there are multiple threads operating on a variable at the same time, who is the variable listening to? First, code:

run's result is

Temporarily solve the multithreading problem of single machine after adding lock lock lock lock under concurrent package

So the problem comes in a distributed environment, different jvm s, how to solve the lock problem?

Think of a famous saying in the field of computing: Any problem in the field of computer science can be solved by adding an indirect middle layer.

This time, zookeeper is the indirect middle layer. The first part introduces the characteristics of zookeeper. As a distributed lock, zookeeper has its unique advantages. At present, the realization scheme of distributed lock known from the market is limited.

1: The disadvantage of using database as distributed lock is obvious.

2: Distributed locks with redis, but the disadvantage of redis is that once the server is locked, it can set expiration time, but it also becomes a bottleneck in this way.

The Benefits/Feasibility of Zookeeper Implementing Distributed Locks

1: Each node can only be created once. The process of creating a node is the process of acquiring locks.

2:zk monitoring mechanism, which monitors the deletion of nodes (lock release), notifies the thread waiting for the lock

3: If a locked server node is down, zk automatically deletes the node as long as the connection is interrupted (to make up for redis deficiency).

The characteristics of zookeeper for implementing distributed locks

1: There are and only one node in the same path

2: Delete the node and recreate it

3: Event notification, which can monitor the status of specified nodes (deletion, change of node data)

The steps for implementing distributed locks are as follows:

1. Opening up two interface methods, acquiring locks and releasing locks

2. Acquisition of locks: 1. Attempt to acquire locks

2. Step 1 succeeds and continues to run; Failure blocks threads waiting to be awakened, and after awakening, continues to attempt to acquire locks.

3. Release Locks, Release Lock Resources Directly

Code implementation:

public abstract class AbstractZkLock implements ZkLockInterface {
    //zk Connection information
    private static final String SERVERSTRING = "127.0.0.1:2181";
    //Node information
    protected static final String LOCK_PATH = "/zkLockPath";
    //Client Connection
    ZkClient zkClient = new ZkClient(SERVERSTRING);


    @Override
    public void getLock()  {
        if (tryLock()) {
            System.out.println("---------------Getting Lock Resources---------------");
        } else {
            //Waiting for the lock blocking operation to wake up indicates that the lock has been released
            waitLock();
            //After release of lockRe-acquisition of locks
            getLock();
        }

    }

    //Waiting for Lock Resources
    abstract void waitLock() ;

    //Attempt to acquire lock resources
    abstract boolean tryLock();


    @Override
    public void unLock() {
        zkClient.close();
    }


}

The above figure is the basic lock operation logic, which mainly operates on the zk implementation code:

public class DistributedZkLock extends AbstractZkLock{

    CountDownLatch countDownLatch = null;

    @Override
    void waitLock() {
        //Monitor
        IZkDataListener iZkDataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                //Node deletion rule detected
                if(countDownLatch != null){
                    countDownLatch.countDown();
                }
            }
        };
        //Registered Event Monitor
        zkClient.subscribeDataChanges(LOCK_PATH,iZkDataListener);

        if(zkClient.exists(LOCK_PATH)) {
       //There is an open semaphore in the path countDownLatch = new CountDownLatch(1); try {
         //Signal blocking awaits event notification wake-up countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } //Blocking End Delete Event Notification zkClient.unsubscribeDataChanges(LOCK_PATH,iZkDataListener); } @Override boolean tryLock() { try {
       //Creating success returns true zkClient.createEphemeral(LOCK_PATH); return true; }catch (Exception e){
       //Creating a failed throw exception returns false return false; } } }

Tags: PHP Zookeeper Redis Java jvm

Posted on Mon, 05 Aug 2019 19:47:44 -0700 by ph3n0m