ReentrantReadWriteLockGroup { public ReentrantReadWriteLock getLock(String id) { ReentrantReadWriteLock lock = locks.get(id); if (lock == null) { locks.putIfAbsent(id, new ReentrantReadWriteLock(fairness)); } lock = locks.get(id); if (CLEANUP_THRESHOLD <= ++counter) { cleanUp(lock); counter = 0; } return lock; } ReentrantReadWriteLockGroup();  ReentrantReadWriteLockGroup(int counter);  ReentrantReadWriteLockGroup(boolean fairness);  ReentrantReadWriteLockGroup(boolean fairness, int counter); ReentrantReadWriteLock getLock(String id);  }
@Test public void ensure_that_consecutive_calls_on_same_string_return_the_same_lock() { ReentrantReadWriteLockGroup locks = new ReentrantReadWriteLockGroup(true, 3); ReentrantReadWriteLock lock1 = locks.getLock("1"); ReentrantReadWriteLock lock2 = locks.getLock("1"); ReentrantReadWriteLock lock3 = locks.getLock("1"); assertEquals(lock1, lock2); assertEquals(lock1, lock3); }
@Test public void ensure_that_calls_with_different_strings_returns_different_locks() { ReentrantReadWriteLockGroup locks = new ReentrantReadWriteLockGroup(true, 3); ReentrantReadWriteLock lock1 = locks.getLock("1"); ReentrantReadWriteLock lock2 = locks.getLock("2"); ReentrantReadWriteLock lock3 = locks.getLock("3"); assertNotEquals(lock1, lock2); assertNotEquals(lock1, lock3); assertNotEquals(lock2, lock3); }
@Test public void ensure_that_a_lock_will_not_be_removed_if_it_is_the_latest_returned_one() { ReentrantReadWriteLockGroup locks = new ReentrantReadWriteLockGroup(true, 1); ReentrantReadWriteLock lock1 = locks.getLock("1"); ReentrantReadWriteLock lock2 = locks.getLock("1"); assertEquals(lock1, lock2); }
@Test public void ensure_that_two_different_locks_are_returned_when_threshold_is_reached() { ReentrantReadWriteLockGroup locks = new ReentrantReadWriteLockGroup(true, 1); ReentrantReadWriteLock firstLockForOneValue = locks.getLock("1"); ReentrantReadWriteLock firstLockForTwoValue = locks.getLock("2"); ReentrantReadWriteLock secondLockForOneValue = locks.getLock("1"); ReentrantReadWriteLock secondLockForTwoValue = locks.getLock("2"); assertNotEquals(firstLockForOneValue, secondLockForOneValue); assertNotEquals(firstLockForTwoValue, secondLockForTwoValue); }
@Test public void ensure_that_two_different_lock_are_returned_when_threshold_is_reached() { ReentrantReadWriteLockGroup locks = new ReentrantReadWriteLockGroup(true, 1); ReentrantReadWriteLock firstLockForOneValue = locks.getLock("1"); Runnable runnable = new Runnable() { @Override public void run() { firstLockForOneValue.writeLock().lock(); } }; Thread t = new Thread(runnable); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } ReentrantReadWriteLock firstLockForTwoValue = locks.getLock("2"); ReentrantReadWriteLock secondLockForOneValue = locks.getLock("1"); assertEquals(firstLockForOneValue, secondLockForOneValue); }