⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadsafeiterator.java

📁 这个是perst-269.zip下面的SOURCECODE,和大家分享了。
💻 JAVA
字号:
package org.garret.perst;

import java.util.Iterator;

/**
 * This class is used to make it possible to iterate collection without locking it and 
 * when cokkection can be currently updated by other threads.
 * Please notice that if other threads are deleting elements from the tree, then
 * deleting current elemet of the iterator can still cause the problem.
 * Also this iterator should be used only inside one thread - sharing iterator between multiple
 * threads will not work correctly.
 */
public class ThreadSafeIterator<T> implements Iterator<T> { 
    private IResource   collection;
    private Iterator<T> iterator;
    private T           next;

    public boolean hasNext() { 
        boolean result;
        if (next == null) {
            collection.sharedLock();
            if (iterator.hasNext()) { 
                next = iterator.next();
                result = true;
            } else { 
                result = false; 
            }
            collection.unlock();
        } else { 
            result = true;
        }
        return result;
    }
    
    public T next() { 
        T obj = next;
        if (obj == null) { 
            collection.sharedLock();
            obj = iterator.next();
            collection.unlock();
        } else { 
            next = null;
        }
        return obj;
    }

    public ThreadSafeIterator(IResource collection, Iterator<T> iterator) { 
        this.collection = collection;
        this.iterator = iterator;
    }

    public void remove() {
        collection.exclusiveLock();
        iterator.remove();
        collection.unlock();
        next = null;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -