Is the following code thread safe?
private static HashMap<String, String> cache = null;
public static String getInfo(String key) {
populateCache();
return cache.containsKey(key) ? cache.get(key) : null;
}
private static void populateCache() {
if (cache == null) {
cache.put("hello", "world");
// ... more population logic here
}
}
If not, what can I do to make it thread safe?
EDIT: Thanks for the answers, I'll try out ConcurrentHashMap. However, I missed out something.. I am actually passing an object of a separate Foo class to getInfo() here:
public static Bar getInfo(Foo object) {
object.someProperty = concurrentHashMapCache.get('something');
return Bar.createFromFoo(object);
}
As long as different threads pass a different Foo object to getInfo, the above code should work, right?