From 39fce59a840b723eb013bc79285687986592b2da Mon Sep 17 00:00:00 2001 From: "Brian S. O'Neill" Date: Sun, 3 Sep 2006 06:14:41 +0000 Subject: More work on query engine. --- .../amazon/carbonado/cursor/IteratorCursor.java | 36 ++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) (limited to 'src/main/java/com/amazon/carbonado/cursor') diff --git a/src/main/java/com/amazon/carbonado/cursor/IteratorCursor.java b/src/main/java/com/amazon/carbonado/cursor/IteratorCursor.java index 0330629..a32b45f 100644 --- a/src/main/java/com/amazon/carbonado/cursor/IteratorCursor.java +++ b/src/main/java/com/amazon/carbonado/cursor/IteratorCursor.java @@ -21,19 +21,44 @@ package com.amazon.carbonado.cursor; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.concurrent.locks.Lock; + +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + /** * Adapts an Iterator into a Cursor. * * @author Brian S O'Neill */ public class IteratorCursor extends AbstractCursor { - private Iterator mIterator; + private static final AtomicReferenceFieldUpdater lockUpdater = + AtomicReferenceFieldUpdater.newUpdater(IteratorCursor.class, Lock.class, "mLock"); + + private volatile Iterator mIterator; + private volatile Lock mLock; /** * @param iterable collection to iterate over, or null for empty cursor */ public IteratorCursor(Iterable iterable) { - this(iterable == null ? (Iterator) null : iterable.iterator()); + this(iterable, null); + } + + /** + * @param iterable collection to iterate over, or null for empty cursor + * @param lock optional lock to hold while cursor is open + */ + public IteratorCursor(Iterable iterable, Lock lock) { + if (iterable == null) { + mIterator = null; + mLock = null; + } else { + if (lock != null) { + lock.lock(); + } + mIterator = iterable.iterator(); + mLock = lock; + } } /** @@ -41,10 +66,17 @@ public class IteratorCursor extends AbstractCursor { */ public IteratorCursor(Iterator iterator) { mIterator = iterator; + mLock = null; } public void close() { mIterator = null; + // Use AtomicReferenceFieldUpdater to allow close method to be safely + // called multiple times without unlocking multiple times. + Lock lock = lockUpdater.getAndSet(this, null); + if (lock != null) { + lock.unlock(); + } } public boolean hasNext() { -- cgit v1.2.3