Java 一直提供一种机制来维护状态并在以后的某个时间点继续执行:线程。我的库解决方案的基本思想是让ConcurrentIterable生产在一个线程中的元素,并让ConcurrentIterator在另一个线程中使用它们,通过有界通信队列。 (这通常被称为生产者/消费者模式。)
首先,这里是一个简化用法的演示:
public class CustomCollection<T> extends ConcurrentIterable<T>
{
private T[] data;
private int size;
@Override
protected void provideElements()
{
for (int i = 0; i < size; ++i)
{
provideElement(data[i]);
}
}
// ...
}
请注意完全没有状态机。您所要做的就是从ConcurrentIterable 派生并实现方法provideElements。在此方法中,您可以编写直接代码,为集合中的每个元素调用 provideElement。
有时客户端不会遍历整个集合,例如在线性搜索中。一旦检测到流产,您可以通过检查iterationAborted() 停止提供元素:
@Override
protected void provideElements()
{
for (int i = 0; i < size && !iterationAborted(); ++i)
{
provideElement(data[i]);
}
}
不检查iterationAborted() 完全没问题,只要您不关心生成的其他元素。对于无限序列,检查iterationAborted() 是强制性的。
生产者如何检测到消费者已停止迭代?这是通过在消费者中对令牌的强引用和对生产者中相同令牌的弱引用来实现的。当消费者停止迭代时,令牌就可以进行垃圾回收,并且最终对生产者来说是不可见的。从那时起,所有新元素都将被丢弃。
(如果没有这种预防措施,在某些情况下,有界队列最终可能会填满,生产者将进入无限循环,并且包含的元素永远不会被垃圾回收。)
现在是实现细节:
ConcurrentIterable.java
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public abstract class ConcurrentIterable<T> implements Iterable<T>
{
private static final int CAP = 1000;
private final ThreadLocal<CommunicationChannel<T>> channels
= new ThreadLocal<CommunicationChannel<T>>();
@Override
public Iterator<T> iterator()
{
BlockingQueue<Option<T>> queue = new ArrayBlockingQueue<Option<T>>(CAP);
Object token = new Object();
final CommunicationChannel<T> channel
= new CommunicationChannel<T>(queue, token);
new Thread(new Runnable()
{
@Override
public void run()
{
channels.set(channel);
provideElements();
enqueueSentinel();
}
}).start();
return new ConcurrentIterator<T>(queue, token);
}
protected abstract void provideElements();
protected final boolean iterationAborted()
{
return channels.get().iterationAborted();
}
protected final void provideElement(T element)
{
enqueue(Option.some(element));
}
private void enqueueSentinel()
{
enqueue(Option.<T> none());
}
private void enqueue(Option<T> element)
{
try
{
while (!offer(element))
{
System.gc();
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
}
}
private boolean offer(Option<T> element) throws InterruptedException
{
CommunicationChannel<T> channel = channels.get();
return channel.iterationAborted()
|| channel.queue.offer(element, 1, TimeUnit.SECONDS);
}
}
CommunicationChannel.java
import java.lang.ref.WeakReference;
import java.util.concurrent.BlockingQueue;
public class CommunicationChannel<T>
{
public final BlockingQueue<Option<T>> queue;
private final WeakReference<Object> token;
public CommunicationChannel(BlockingQueue<Option<T>> queue, Object token)
{
this.queue = queue;
this.token = new WeakReference<Object>(token);
}
public boolean iterationAborted()
{
return token.get() == null;
}
}
ConcurrentIterator.java
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
public class ConcurrentIterator<T> implements Iterator<T>
{
private final BlockingQueue<Option<T>> queue;
@SuppressWarnings("unused")
private final Object token;
private Option<T> next;
public ConcurrentIterator(BlockingQueue<Option<T>> queue, Object token)
{
this.queue = queue;
this.token = token;
}
@Override
public boolean hasNext()
{
if (next == null)
{
try
{
next = queue.take();
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
}
}
return next.present;
}
@Override
public T next()
{
if (!hasNext()) throw new NoSuchElementException();
T result = next.value;
next = null;
return result;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
Option.java
public class Option<T>
{
public final T value;
public final boolean present;
private Option(T value, boolean present)
{
this.value = value;
this.present = present;
}
public static <T> Option<T> some(T value)
{
return new Option<T>(value, true);
}
@SuppressWarnings("unchecked")
public static <T> Option<T> none()
{
return none;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static final Option none = new Option(null, false);
}
让我知道你的想法!