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.
ConcurrentHashMap(andMap/ConcurrentMapin general) won’t throw an exception if the specified key doesn’t exist. That’s why theremovemethod returns aboolean, to indicate whether or not anything was actually removed.But yes, you can lock on the local variable. After all, you’re really locking via a reference (and the monitor associated with the referenced object), not a variable – and the other concurrently running method would have the same reference.