[concurrency-interest] Design of Thread Safe Iterator Proxy

piyush katariya corporate.piyush at gmail.com
Mon Jun 10 02:37:57 EDT 2013


Hi,

       so i was in the need of ThreadSafe iterator, so that multiple
threads can access over it concurrently without  throwing
"ConcurrentModificationException".

i came with solution attached herewith, but for some reason..multiple
threads from thread pool after iterating over, stucks...

can somebody help me with it..


Regards,
Piyush Katariya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20130610/f015fcbc/attachment-0001.html>
-------------- next part --------------
package org.jhighfun.util.batch;

import java.util.Iterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Thread safe proxy for existing Iterator
 *
 * @author Piyush Katariya
 */
public class SafeIterator<T> implements Iterator<T> {

    private final Iterator<T> iterator;
    private final Lock lock = new ReentrantLock();

    public SafeIterator(Iterator<T> iterator) {
        this.iterator = iterator;
    }

    public boolean hasNext() {
        lock.lock();
        boolean hasNext = false;
        try {
            hasNext = iterator.hasNext();
        } catch (Exception e) {
            lock.unlock();
        }
        return hasNext;
    }

    public T next() {
        T next = null;
        try {
            next = iterator.next();
        } finally {
            lock.unlock();
        }
        return next;
    }

    public void remove() {
        lock.lock();
        try {
            iterator.remove();
        } finally {
            lock.unlock();
        }
    }
}


More information about the Concurrency-interest mailing list