Skip to content

Instantly share code, notes, and snippets.

@jsanda
Created November 2, 2016 16:12
Show Gist options
  • Save jsanda/802a410514b406f08514c8fe7c5669cc to your computer and use it in GitHub Desktop.
Save jsanda/802a410514b406f08514c8fe7c5669cc to your computer and use it in GitHub Desktop.
@Listener
public class DistributedLock {
private static Logger log = Logger.getLogger(DistributedLock.class);
private static final String KEY = "cassalog";
private AdvancedCache<String, String> locksCache;
public DistributedLock(AdvancedCache<String, String> locksCache) {
this.locksCache = locksCache;
this.locksCache.getCacheManager().addListener(this);
}
public boolean isLocked() {
return getLockValue().equals(locksCache.get(KEY));
}
public boolean lock() {
if (isLocked()) {
return true;
}
String previous = locksCache.putIfAbsent(KEY, getLockValue());
return previous == null;
}
public boolean release() {
if (isLocked()) {
return locksCache.remove(KEY, getLockValue());
}
return false;
}
@ViewChanged
public void viewChanged(ViewChangedEvent event) {
log.info("view changed: " + event);
List<Address> old = new ArrayList<>(event.getOldMembers());
old.removeAll(event.getNewMembers());
for (Address address : old) {
locksCache.remove(KEY, address.toString());
}
}
private String getLockValue() {
EmbeddedCacheManager cacheManager = locksCache.getCacheManager();
Address address = cacheManager.getAddress();
return address.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment