Created
April 21, 2014 20:35
-
-
Save jartur/11155701 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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