View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.util;
20  
21  import org.apache.hadoop.hbase.testclassification.SmallTests;
22  import org.junit.Assert;
23  import org.junit.Test;
24  import org.junit.experimental.categories.Category;
25  
26  import java.util.concurrent.locks.ReentrantLock;
27  
28  @Category(SmallTests.class)
29  public class TestKeyLocker {
30    @Test
31    public void testLocker(){
32      KeyLocker<String> locker = new KeyLocker();
33      ReentrantLock lock1 = locker.acquireLock("l1");
34      Assert.assertTrue(lock1.isHeldByCurrentThread());
35  
36      ReentrantLock lock2 = locker.acquireLock("l2");
37      Assert.assertTrue(lock2.isHeldByCurrentThread());
38      Assert.assertTrue(lock1 != lock2);
39  
40      // same key = same lock
41      ReentrantLock lock20 = locker.acquireLock("l2");
42      Assert.assertTrue(lock20 == lock2);
43      Assert.assertTrue(lock2.isHeldByCurrentThread());
44      Assert.assertTrue(lock20.isHeldByCurrentThread());
45  
46      // Locks are still reentrant; so with 2 acquires we want two unlocks
47      lock20.unlock();
48      Assert.assertTrue(lock20.isHeldByCurrentThread());
49  
50      lock2.unlock();
51      Assert.assertFalse(lock20.isHeldByCurrentThread());
52  
53      // The lock object was freed once useless, so we're recreating a new one
54      ReentrantLock lock200 = locker.acquireLock("l2");
55      Assert.assertTrue(lock2 != lock200);
56      lock200.unlock();
57      Assert.assertFalse(lock200.isHeldByCurrentThread());
58  
59      // first lock is still there
60      Assert.assertTrue(lock1.isHeldByCurrentThread());
61      lock1.unlock();
62      Assert.assertFalse(lock1.isHeldByCurrentThread());
63    }
64  }