Package org.zkoss.util
Class WaitLock
- java.lang.Object
-
- org.zkoss.util.WaitLock
-
public class WaitLock extends java.lang.Object
A simple lock used to implement load-on-demand 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 callswaitUntilUnlock(int)
to wait. Meanwhile, once A completes the loading, it put back the resource and callsunlock()
.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(); }
- Author:
- tomyeh
-
-
Constructor Summary
Constructors Constructor Description WaitLock()
Once created, it is default to be locked.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
unlock()
Unlocks any other threads blocked bywaitUntilUnlock(int)
.boolean
waitUntilUnlock(int timeout)
Waits this lock to unlock.
-
-
-
Constructor Detail
-
WaitLock
public WaitLock()
Once created, it is default to be locked. In other words, other thread's invocation ofwaitUntilUnlock(int)
won't return untilunlock()
is called.
-
-
Method Detail
-
waitUntilUnlock
public boolean waitUntilUnlock(int timeout)
Waits this lock to unlock.- Returns:
- whether it is unlocked successfully
- Throws:
SystemException
- if this thread is interruptedPotentialDeadLockException
- if the thread itself creates this lock. In other words, it tried to wait for itself to complete.
-
unlock
public void unlock()
Unlocks any other threads blocked bywaitUntilUnlock(int)
.
-
-