View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.zookeeper.lock;
21  
22  import java.io.IOException;
23  import java.util.List;
24  import java.util.SortedSet;
25  import java.util.TreeSet;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
31  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
32  
33  /**
34   * ZooKeeper based read lock: does not exclude other read locks, but excludes
35   * and is excluded by write locks.
36   */
37  @InterfaceAudience.Private
38  public class ZKInterProcessReadLock extends ZKInterProcessLockBase {
39  
40    private static final Log LOG = LogFactory.getLog(ZKInterProcessReadLock.class);
41  
42    public ZKInterProcessReadLock(ZooKeeperWatcher zooKeeperWatcher,
43        String znode, byte[] metadata, MetadataHandler handler) {
44      super(zooKeeperWatcher, znode, metadata, handler, READ_LOCK_CHILD_NODE_PREFIX);
45    }
46  
47    /**
48     * {@inheritDoc}
49     */
50    @Override
51    protected String getLockPath(String createdZNode, List<String> children) throws IOException {
52      TreeSet<String> writeChildren =
53          new TreeSet<String>(ZNodeComparator.COMPARATOR);
54      for (String child : children) {
55        if (isChildWriteLock(child)) {
56          writeChildren.add(child);
57        }
58      }
59      if (writeChildren.isEmpty()) {
60        return null;
61      }
62      SortedSet<String> lowerChildren = writeChildren.headSet(createdZNode);
63      if (lowerChildren.isEmpty()) {
64        return null;
65      }
66      String pathToWatch = lowerChildren.last();
67      String nodeHoldingLock = lowerChildren.first();
68      String znode = ZKUtil.joinZNode(parentLockNode, nodeHoldingLock);
69      handleLockMetadata(znode);
70  
71      return pathToWatch;
72    }
73  }