SomeContainer Set<element> elements; ReadWriteLock globalLock; Lock readLock; Lock writeLock; SomeContainer() elements = HashSet<element>(); globalLock = ReentrantReadWriteLock(); readLock = globalLock.readLock(); writeLock = globalLock.writeLock(); addElement(Element elem) writeLock.lock(); elements.add(elem); writeLock.unlock(); processElements(ElementProcessor processor) readLock.lock(); Iterator<element> iter = elements.iterator(); (iter.hasNext()) Element element = iter.next(); processor.processElement(element); readLock.unlock(); ElementProcessor processElement(Element element);</element></element></element>
So, in the example above, the first line in processElements
will let everybody play at once so long as the write lock is not held. Then, when the write lock is requested, the requesting thread will be made to wait until all existing readers are done (no further readers will be let in), and then the writer thread may begin.