| A simple lock used to implement load-on-deman mechanism.
Typical use: a thread, say A, checks whether a resource is loaded, and
put a WaitLock instance if not loaded yet. Then, another thread, say B,
if find WaitLock, it simply calls
WaitLock.waitUntilUnlock to wait.
Meanwhile, once A completes the loading, it put back the resouce
and calls
WaitLock.unlock .
WaitLock lock = null;
for (;;) {
synchronized (map) {
Object o = map.get(key);
if (o == null) {
map.put(key, lock = new WaitLock());
break; //go to load resource
}
}
if (o instanceof MyResource)
return (MyResource)o;
if (!((Lock)o).waitUntilUnlock(60000))
log.waring("Takes too long");
}
//load resource
try {
....
synchronized (map) {
map.put(key, resource);
}
return resource;
} catch (Throwable ex) {
synchronized (map) {
map.remove(key);
}
throw SystemException.Aide.wrap(ex);
} finally {
lock.unlock();
}
Refer to i3sys's SketchPostImpl, zweb's JspLoaderServlet for examples.
author: tomyeh |