LockManagerImpl implements LockManager { @Override public ILock acquireLock(final ILockKey lockKey, final String user) throws LockException { return storage.write(storeProvider -> { LockStore.Mutable lockStore = storeProvider.getLockStore(); Optional<ILock> existingLock = lockStore.fetchLock(lockKey); if (existingLock.isPresent()) { throw new LockException(String.format( "Operation for: %s is already in progress. Started at: %s. Current owner: %s.", formatLockKey(lockKey), new Date(existingLock.get().getTimestampMs()).toString(), existingLock.get().getUser())); } ILock lock = ILock.build(new Lock() .setKey(lockKey.newBuilder()) .setToken(tokenGenerator.createNew().toString()) .setTimestampMs(clock.nowMillis()) .setUser(user)); lockStore.saveLock(lock); return lock; }); } @Inject  LockManagerImpl(Storage storage, Clock clock, UUIDGenerator tokenGenerator); @Override ILock acquireLock(final ILockKey lockKey, final String user); @Override void releaseLock(final ILock lock); @Override void assertNotLocked(final ILockKey context); @Override Iterable<ILock> getLocks();  }
@Test public void testAcquireLock() throws Exception { control.replay(); ILock expected = ILock.build(new Lock() .setKey(LOCK_KEY.newBuilder()) .setToken(TOKEN.toString()) .setTimestampMs(timestampMs) .setUser(USER)); ILock actual = lockManager.acquireLock(expected.getKey(), USER); assertEquals(expected, actual); }
@Test public void testAcquireLockInProgress() throws Exception { control.replay(); expectLockException(JOB_KEY); lockManager.acquireLock(LOCK_KEY, USER); lockManager.acquireLock(LOCK_KEY, USER); }