I\'ve got a web application where people ask for resources. This resources are cached using a synchronized hash map for efficiency. The problem here is when two different re
The only potential problem I see is that you synchronize to this
. If any other code in the same class also synchronizes to this
, only one of those blocks will run at once. Maybe there's nothing else that does this, and that's fine. I always worry about what the next programmer is going to do, though. (or myself in three months when I've forgotten about this code)
I would recommend creating a generic synch object and then synch'ing to that.
private final Object resourceCreationSynchObject = new Object();
then
synchronized(this.resourceCreationSynchObject) { ... }
Otherwise, this does exactly what you're asking for. It ensures that veryCostlyOperation
cannot be called in parallel.
Also, it's great thinking to re-get the resource a second time within the synchronized
block. This is necessary, and the first call outside makes sure that you don't synchronize when the resource is already available. But there's no reason to call it a third time. First thing inside the synchronized
block, set resource
again to resources.get(name)
and then check that variable for null. That will prevent you from having to call get
again inside the else
clause.