Skip to content

Instantly share code, notes, and snippets.

@jartur
Created April 21, 2014 20:35
Show Gist options
  • Save jartur/11155701 to your computer and use it in GitHub Desktop.
Save jartur/11155701 to your computer and use it in GitHub Desktop.
AtomicReference<Map> amap;
readOnlyMethod() {
// get immutable map reference
Map m = amap.get();
m.get(key);
...
m.get(key2);
...
}
writeMethod() {
boolean success = false;
// retry ALL operations if map has changed while we were updating
while(!success) {
// get immutable map reference
Map original = amap.get();
// create a copy
Map updated = new Map(original);
// modify map
updated.put(key, value);
...
// here we can use data from map, of course
// this is one of the reasons we have to retry
// basically it's like a transaction. That's why it's called Software Transactional Memory
if(updated.get(key1).equals(something)) {
updated.put(key2, value2);
}
//save new map
success = amap.cas(original, updated);
// here we can add some randomized algorithm for back off *if writes are frequent*
Thread.sleep(System.currentTimeMillis() % 5);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment