[英]Java - Concurrent processing with a common executor service instance
我有 n 个工作线程从 kinesis 流中检索记录(这对于这个问题并不重要),然后将其推送到执行程序服务,在该服务中记录被处理并保存到后端数据库。 这个相同的执行程序服务实例用于所有工作线程。
现在有一个场景,任何给定的工作循环停止处理记录并阻塞,直到它提交的所有记录都被完全处理。 这实质上意味着对于来自该特定工作线程的记录,执行程序服务中不应该有挂起/正在运行的线程。
一个非常简单的实现例子是这样的:
工人阶级
public class Worker { Worker(Listener listener){ this.listener = listener; } //called periodically to fetch records from a kinesis stream public void processRecords(Record records) { for (Record record : records) { listener.handleRecord(record); } //if 15 minutes has elapsed, run below code. This is blocking. listener.blockTillAllRecordsAreProcessed() }
}
监听类
public class Listener { ExecutorService es; // same executor service is shared across all listeners. Listener(ExecutorService es){ this.es = es; } public void handleRecord(Record record) { //submit record to es and return // non blocking } public boolean blockTillAllRecordsAreProcessed(){ // this should block until all records are processed // no clue how to implement this with a common es } }
我能想到的唯一方法是为每个工作人员提供一个本地执行程序服务,并为每个批次执行诸如invokeAll
的操作,这将稍微更改实现但完成工作。 但我觉得应该有更好的方法来解决这个问题。
您可以使用 CountdownLatch 类来阻止,如下所示:
public void processRecords(List<Record> records) {
CountDownLatch latch = new CountDownLatch(records.size());
for (Record record : records) {
listener.handleRecord(record, latch);
}
//if 15 minutes has elapsed, run below code. This is blocking.
listener.blockTillAllRecordsAreProcessed(latch)
}
public class Listener {
ExecutorService es;
...
public void handleRecord(Record record, CountDownLatch latch) {
//submit record to es and return
// non blocking
es.submit(()->{
someSyncTask(record);
latch.countDown();
})
}
public boolean blockTillAllRecordsAreProcessed(CountDownLatch latch){
System.out.println("waiting for processes to complete....");
try {
//current thread will get notified if all chidren's are done
// and thread will resume from wait() mode.
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在此处阅读更多信息: https : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.