Java Docs says that, putIfAbsent
is equivalent to
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key
Your code will throw an NPE if the key was not previously in the map.
Other than that, although this is a reasonable idea, it will not work in a "concurrent" environment. The reason the putIfAbsent()
method was added was so that the map could manage the atomicity of the operation using whatever underlying support it is using to make the operations thread-safe. In your implementation, 2 different callers could end of stepping on each other (the first replaces an expired value with a new one, and the second immediately replaces the first new one with a second new one).