I have this snippet of code
private Templates retrieveFromCache(String name) {
TemplatesWrapper t = xlCache.get(name);
synchronized(t){
if (!t.isValid()) {
xlCache.remove(name);
return null;
}
}
return t.getTemplate();
}
xlCache
is a ConcurrentHashMap
; my reason for synchronizing on t
is that 2 threads could interleave where by the time Thread 1 verifies the predicate Thread 2 has already removed the object from the map and then a NullPointerException
would be thrown. Is my assumption correct as I know concurrency is one of the more difficult things to reason about. And then to my original question, can I lock on t
even if it's local?
And this is private
method as well which gets called from a public
method, does it make a diff?
EDIT: MY original premise that a NullPointerException
is thrown was incorrect as remove()
returns boolean
making synchronization moot; however, my question was of locking on a local object was answered.