【发布时间】:2015-02-12 17:46:45
【问题描述】:
过去我写过一些java程序,使用两个线程。 第一个线程(生产者)从 API(C 库)读取数据,创建一个 java 对象,将对象发送到另一个线程。 C API 正在传递事件流(无限)。 线程使用 LinkedBlockingQueue 作为管道来交换对象(put、poll)。 第二个线程(消费者)正在处理对象。 (我还发现代码在线程中更具可读性。第一个线程正在处理 C API 内容并生成 正确的 java 对象,第二个线程不受 C API 处理并正在处理数据)。
现在我很感兴趣,如何使用 Java 8 中的新流 API 实现上述场景。 但假设我想保留两个线程(生产者/消费者)! 第一个线程正在写入流。第二个线程正在从流中读取。 我也希望,我可以用这种技术处理更好的显式并行性(生产者/消费者) 并且在流中我可以使用一些隐式并行性(例如stream.parallel())。
我对新的流 api 没有太多经验。 于是我尝试了下面的代码,来解决上面的思路。
- 我使用“生成”来访问 C API 并将其提供给 java 流。
- 我在消费者线程中使用 .parallel() 来测试和处理隐式并行性。看起来不错。但见下文。
问题:
- 在这种情况下,对于生产者来说,“生成”是最佳方式吗?
- 我对如何终止/关闭生产者中的流有一个理解问题,
如果 API 有一些错误并且我想关闭整个管道。
我是使用 stream.close 还是抛出异常?
- 2.1 我使用了stream.close()。但是“生成”在关闭后仍在运行, 我发现只有抛出异常来终止生成部分。 此异常正在进入流中,并且消费者正在接收异常 (这对我来说很好,消费者可以识别并终止)。 但是在这种情况下,生产者生产的比消费者处理的多,而异常正在到来。
- 2.2 如果消费者使用隐式并行stream.parallel()。生产者正在处理更多的项目。 所以我看不到这个问题的任何解决方案。 (访问 C API,检查错误,做出决定)。
- 2.3 生产者抛出异常到达消费者流,但并非所有插入的对象都被处理。
再一次:这个想法是与线程有明确的并行性。 但在内部,我可以处理新功能并尽可能使用并行处理
也感谢您提出这个问题。
package sandbox.test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.LongStream;
public class MyStream {
private volatile LongStream stream = null;
private AtomicInteger producerCount = new AtomicInteger(0);
private AtomicInteger consumerCount = new AtomicInteger(0);
private AtomicInteger apiError = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
MyStream appl = new MyStream();
appl.create();
}
private static void sleep(long sleep) {
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static void apiError(final String pos, final int iteration) {
RuntimeException apiException = new RuntimeException("API error pos=" + pos + " iteration=" + iteration);
System.out.println(apiException.getMessage());
throw apiException;
}
final private int simulateErrorAfter = 10;
private Thread produce() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Producer started");
stream = LongStream.generate(() -> {
int localCount;
// Detect error, while using stream.parallel() processing
int error = apiError.get();
if ( error > 0 )
apiError("1", error);
// ----- Accessing the C API here -----
localCount = producerCount.incrementAndGet(); // C API access; delegate for accessing the C API
// ----- Accessing the C API here -----
// Checking error code from C API
if ( localCount > simulateErrorAfter ) { // Simulate an API error
producerCount.decrementAndGet();
stream.close();
apiError("2", apiError.incrementAndGet());
}
System.out.println("P: " + localCount);
sleep(200L);
return localCount;
});
System.out.println("Producer terminated");
}
});
thread.start();
return thread;
}
private Thread consume() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
stream.onClose(new Runnable() {
@Override
public void run() {
System.out.println("Close detected");
}
}).parallel().forEach(l -> {
sleep(1000);
System.out.println("C: " + l);
consumerCount.incrementAndGet();
});
} catch (Exception e) {
// Capturing the stream end
System.out.println(e);
}
System.out.println("Consumer terminated");
}
});
thread.start();
return thread;
}
private void create() throws InterruptedException {
Thread producer = produce();
while ( stream == null )
sleep(10);
Thread consumer = consume();
producer.join();
consumer.join();
System.out.println("Produced: " + producerCount);
System.out.println("Consumed: " + consumerCount);
}
}
【问题讨论】:
-
我认为您正在寻找一个响应式框架,例如 RxJava。有了足够大的撬棍,你可以强制 Streams 做你想做的事,但你最好使用专为这项工作设计的工具。
标签: java multithreading parallel-processing java-8 java-stream