簡體   English   中英

Java - 使用通用執行程序服務實例進行並發處理

[英]Java - Concurrent processing with a common executor service instance

我有 n 個工作線程從 kinesis 流中檢索記錄(這對於這個問題並不重要),然后將其推送到執行程序服務,在該服務中記錄被處理並保存到后端數據庫。 這個相同的執行程序服務實例用於所有工作線程。

現在有一個場景,任何給定的工作循環停止處理記錄並阻塞,直到提交所有記錄都被完全處理。 這實質上意味着對於來自該特定工作線程的記錄,執行程序服務中不應該有掛起/正在運行的線程。

一個非常簡單的實現例子是這樣的:

  1. 工人階級

    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() }

    }

  2. 監聽類

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM