Created
June 24, 2015 19:31
-
-
Save buchgr/24f68bfa62897e3a9af8 to your computer and use it in GitHub Desktop.
Double-Checked Locking with a Map
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
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