[concurrency-interest] Thread-safe iterator

Johannes.Lichtenberger Johannes.Lichtenberger at uni-konstanz.de
Fri Feb 17 00:55:43 EST 2012


I want to write a thread safe iterator for a DescendantAxis which
returns all descendants of a node in a tree-structure.

All movement is done within a transaction (the mRtx instance):

    public synchronized final long nextNode() {
        synchronized (mRtx) {
            long retVal = -1;
            if (hasNext()) {
                retVal = next();
            return retVal;

The "iterator" returns all unique nodeIDs. hasNext() and next() are
implementations of the Iterable<T> interface. As I'm synchronizing on
the transaction reference I think it's safe (mRtx is also declared
"final"). Should be safe even if hasNext() and next() are not
synchronized as the first thing is a movement in hasNext():

     * Make sure the transaction points to the node after the last
{@code hasNext()}.
     * This must be called first in {@code hasNext()}.
     * @return key of node where transaction was after the last call of
     *         {@code hasNext()}
    protected final long resetToLastKey() {
        // No check because of IAxis Convention 4.
        mNext = true;
        return mKey;

Did I miss something?

kind regards,

More information about the Concurrency-interest mailing list