### Question:
LockFactory { public Lock acquireLock(K key) { if (key == null) { throw new NullPointerException("Key must not be null"); } final Key<K> internalKey = new Key<K>(key); Lock lock; synchronized (lockCache) { final Reference<Lock> holder = lockCache.get(internalKey); if (holder == null || (lock = holder.get()) == null) { lock = new KeyReferenceLock<K>(internalKey); lockCache.put(internalKey, new WeakReference<Lock>(lock)); } } return lock; } LockFactory(); Lock acquireLock(K key);  }### Answer:
@Test public void ensureLocksAreUnique() { LockFactory<String> stringLockFactory = new LockFactory<String>(); Lock lockA = stringLockFactory.acquireLock("abc"); Lock lockB = stringLockFactory.acquireLock("def"); assertThat(lockA).isNotEqualTo(lockB); LockFactory<Integer> intLockFactory = new LockFactory<Integer>(); Lock lockC = intLockFactory.acquireLock(5); Lock lockD = intLockFactory.acquireLock(10); assertThat(lockC).isNotEqualTo(lockD); }
@Test public void ensureLocksAreShared() { LockFactory<String> stringLockFactory = new LockFactory<String>(); Lock lockA = stringLockFactory.acquireLock("xyz"); Lock lockB = stringLockFactory.acquireLock("xyz"); assertThat(lockA).isEqualTo(lockB); LockFactory<Integer> intLockFactory = new LockFactory<Integer>(); Lock lockC = intLockFactory.acquireLock(new Integer(5)); Lock lockD = intLockFactory.acquireLock(new Integer(5)); assertThat(lockC).isEqualTo(lockD); }
@Test(enabled = false) public void verifyCleanUp() { LockFactory<String> lockFactory = new LockFactory<String>(); Lock lockA = lockFactory.acquireLock("abc"); Lock lockB = lockFactory.acquireLock("abc"); assertThat(lockA).isEqualTo(lockB); int hashCodeA = lockA.hashCode(); int hashCodeB = lockB.hashCode(); assertThat(hashCodeA).isEqualTo(hashCodeB); lockA = null; lockB = null; System.gc(); Lock lockC = lockFactory.acquireLock("abc"); int hashCodeC = lockC.hashCode(); assertThat(hashCodeA).isEqualTo(hashCodeB).isNotEqualTo(hashCodeC); }
@Test(expectedExceptions = NullPointerException.class) public void verifyDisallowNullKey() { LockFactory<String> lockFactory = new LockFactory<String>(); lockFactory.acquireLock(null); }