Skip to content

Instantly share code, notes, and snippets.

@egcodes
Last active March 17, 2022 10:56
Show Gist options
  • Save egcodes/66ba7d508d6e6dac00c58497a0a3e34c to your computer and use it in GitHub Desktop.
Save egcodes/66ba7d508d6e6dac00c58497a0a3e34c to your computer and use it in GitHub Desktop.
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class DistributedLockProviderImpl implements DistributedLockProvider {
private final LockProvider lockProvider;
@Override
public DistLock lock(String key, int lockAtLeastFor, int lockAtMostFor) {
var lockConfiguration = new LockConfiguration(Instant.now(), key,
Duration.ofMillis(lockAtMostFor),
Duration.ofMillis(lockAtLeastFor)
);
return new DistLock(lockProvider.lock(lockConfiguration));
}
public class DistLock implements AutoCloseable {
private Optional<SimpleLock> lock;
public DistLock(Optional<SimpleLock> lock) {
this.lock = lock;
}
public boolean isPresent() {
return lock.isPresent();
}
public boolean isEmpty() {
return lock.isEmpty();
}
@Override
public void close() {
lock.ifPresent(SimpleLock::unlock);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment