Skip to content

Instantly share code, notes, and snippets.

@buchgr
Created June 24, 2015 19:31
Show Gist options
  • Save buchgr/24f68bfa62897e3a9af8 to your computer and use it in GitHub Desktop.
Save buchgr/24f68bfa62897e3a9af8 to your computer and use it in GitHub Desktop.
Double-Checked Locking with a Map
class Main {
private final Map<Integer, Object> map = new ConcurrentHashMap<>();
public Object getOnce(int idx) {
Object obj = map.get(idx);
if (obj == null) {
synchronized(this) {
obj = map.get(idx);
if (obj == null) {
obj = new Object();
map.put(idx, obj);
}
}
}
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment