001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import static org.junit.jupiter.api.Assertions.assertFalse; 021import static org.junit.jupiter.api.Assertions.assertNotEquals; 022import static org.junit.jupiter.api.Assertions.assertTrue; 023 024import java.util.concurrent.locks.ReentrantLock; 025import org.apache.hadoop.hbase.testclassification.MiscTests; 026import org.apache.hadoop.hbase.testclassification.SmallTests; 027import org.junit.jupiter.api.Tag; 028import org.junit.jupiter.api.Test; 029 030@Tag(MiscTests.TAG) 031@Tag(SmallTests.TAG) 032public class TestKeyLocker { 033 034 @Test 035 public void testLocker() { 036 KeyLocker<String> locker = new KeyLocker<>(); 037 ReentrantLock lock1 = locker.acquireLock("l1"); 038 assertTrue(lock1.isHeldByCurrentThread()); 039 040 ReentrantLock lock2 = locker.acquireLock("l2"); 041 assertTrue(lock2.isHeldByCurrentThread()); 042 assertTrue(lock1 != lock2); 043 044 // same key = same lock 045 ReentrantLock lock20 = locker.acquireLock("l2"); 046 assertTrue(lock20 == lock2); 047 assertTrue(lock2.isHeldByCurrentThread()); 048 assertTrue(lock20.isHeldByCurrentThread()); 049 050 // Locks are still reentrant; so with 2 acquires we want two unlocks 051 lock20.unlock(); 052 assertTrue(lock20.isHeldByCurrentThread()); 053 054 lock2.unlock(); 055 assertFalse(lock20.isHeldByCurrentThread()); 056 057 // The lock object will be garbage-collected 058 // if you free its reference for a long time, 059 // and you will get a new one at the next time. 060 int lock2Hash = System.identityHashCode(lock2); 061 lock2 = null; 062 lock20 = null; 063 064 System.gc(); 065 System.gc(); 066 System.gc(); 067 068 ReentrantLock lock200 = locker.acquireLock("l2"); 069 assertNotEquals(lock2Hash, System.identityHashCode(lock200)); 070 lock200.unlock(); 071 assertFalse(lock200.isHeldByCurrentThread()); 072 073 // first lock is still there 074 assertTrue(lock1.isHeldByCurrentThread()); 075 lock1.unlock(); 076 assertFalse(lock1.isHeldByCurrentThread()); 077 } 078}