0

依存関係を持つオブジェクトを作成しようとしています。ポイントは、ExecutorServiceを持つクラスとRunnableを生成するクラスが異なることです。ここでは、単純な抽象化です:ExecutorServiceに渡すことができ、実行可能ファイル間の依存関係を持つオブジェクト

public class Main { 
    private ExecutorService pool; // Initialized before executing main 
    public static void main(String[] args) { 
    List<Batch> batches = // fetching... 
    for(Batch batch : batches) { 
     Runnable r = batch.getRunnable(); 
     pool.submit(r); 
    } 
    } 
} 

public class Batch { 
    public Runnable getRunnable() { 
    Runnable r1 = // creating... 
    Runnable r2 = // creating... 
    // FIXME: demand that r2 run after r1 finishes 
    return // something suitable. r1? r2? or new Runnable? 
    } 
} 

これらのクラスが1のとき、私はCompletableFutureを使用するために使用される:

CompletableFuture.runAsync(r1, pool) 
       .thenRunAsync(r2, pool) 
       .exceptionally(ex -> { // Do something }); 

しかし、今poolは別のクラスに存在します。私はCompletableFutureクラスのドキュメントをもっと見ていますが、まだそれが助けになるかどうかはわかりません。

誰もがここで何か知識を持っていますか?

+0

あなたの 'Batch'が' Runnable'のリストを返せば十分ではないでしょうか?そして、あなたが以前使ったように 'runAsync'と' thenRunAsync'を使うことができます。 – samjaf

+0

このように実装することもできますが、上記が達成されれば、整然とした柔軟な実装になると思います。それは奇妙な要件ですか? – tsuda7

答えて

1

線形の依存関係のために、あなただけの作業を一つずつ実行する新しいRunnableを返すことができます。このようにして、実行順序を完全に制御できます。 Runnableのリストは注文を保証するものではありません。契約を尊重するためには他のクラスも必要です。

public Runnable getRunnable() { 
    Runnable r1 = ... 
    Runnable r2 = ... 
    return()->{ 
     r1.run(); 
     r2.run(); 
    }; 
} 

私は実際にいつRunnable Depenency Graphをサポートしているのか分かりませんでした。私は時間を取った後でコード化しようとします。

+0

ありがとう、それは非常に役に立つようです! – tsuda7

1

Batchクラスは、順番に処理する必要があるRunnableの数を提供すると考えられます。だからRunnableを別のRunnableの中にカプセル化すると、多くのものに隠れるかもしれません。

しかし、私は簡単な解決策は、可能性がダウンRunnableにコードを単純化するためにあなたの条件を理解してください:もちろん

public class Batch implements Runnable{ 
    public List<Runnable> getRunnable() { 
    Runnable r1 = // creating... 
    Runnable r2 = // creating... 
    // FIXME: demand that r2 run after r1 finishes 
    return // List of r1, r2, .... 
} 

@Override 
public void run(){ 
    for (Runnable r:getRunnable()){ 
     r.run(); 
    } 
} 

あなたのバッチがRunnableのシリーズとして1 Runnableないとして処理されますこの方法。編集

BatchたらRunnable実装

、あなたのクラスMainは、次のようになります。

public class Main { 
    private ExecutorService pool; // Initialized before executing main 
    public static void main(String[] args) { 
    List<Batch> batches = // fetching... 
    for(Batch batch : batches) { 
     pool.submit(batch); 
    } 
    } 
} 
+0

私は別のクラス 'Main'にExecuteServiceを持っているので、' Batch'自体は単独では実行できません。しかし、あなたの答えは大変ありがとう! – tsuda7

+0

「ExecutorServices」がどこにあるかは、どのように関係しているのでしょうか。 'Batch'が' Runnable'を実装している場合、それをエグゼキュータに送ることができます。 – samjaf

関連する問題