-2

高速な分類サービスを提供する必要があるクラスがあります。たとえば、「classify("Ac Kd Kh 3c 3s")」のように TWO_PAIR をすばやく返すコードを書きたいとします。(これはアプリケーションではありませんが、概要はわかります)

迅速に分類する必要があるため、考えられるすべての入力の分類出力を一覧表示するルックアップ テーブルを事前に計算して保存します。時間の都合上、この事前計算を並列化したいと考えています。ただし、2 番目のスレッドから「classifySlowly」を使用しようとすると、デッドロックが発生します。

public class Classifcation Service {
  enum CLASS {TYPE_A, TYPE_B, ...};

  static CLASS[] preComputedClassLookUpTable;

  static {
    preComputedClassLookUpTable = constructLookUpTableInParallel();
  }

  //Note: using this method from with constructLookUpTableInParallel causes deadlock
  private static CLASS classifySlowly(Object classifyMe) {
    //do time intensive work to classify the input
    // -- uses no other methods from this class
    return classification;
  }

  public static CLASS classify(Object classifyMe) {
    //use the lookup table to do a quick classification
    return classification;
  }   
}

だから私の質問は:静的初期化ブロック内からこのルックアップテーブルを並列に事前計算する方法はありますか?

私が見る唯一の(貧弱な)代替手段は、次から切り替えることです:

preComputedClassLookUpTable = constructLookUpTableInParallel();

に:

preComputeClassLookUpTable = loadLookUpTableFromFile();
if(preComputedClassLookUpTable == null) {
  System.out.println("WARNING:  Construction incomplete, Must call computeAndSaveLookUpTableFile();}
}

これは多すぎると思いましたが、ここにconstructLookUpTableInParallelの実装があります

private static CLASS[] constructLookUpTableInParallel() {

  //build a collection of Runnables by iterating over all possible input Objects
  //wrap each possible input in an anonymous Runnable that calls classifySlowly.

  //submit the collection of Runnables to a new ExecutorService
  //process runnables...
  //shutdown executor service      
}

////////お粗末な元の質問の終わり///////////

ある程度きれいに機能する解決策は、classifySlowly(Object classifyMe) メソッドと classify(Object classifyMe) メソッドを 2 つの異なるクラスに分割することです。

これにより、「public static CLASS classifySlowly(Object classifyMe)」を含む (最初の) クラスは、「public static CLASS classifyQuickly(Object classifyMe)」を含む (2 番目の) クラスが classifySlowly メソッドを使用する必要があるまでに完全にロードされます。 . これで、2 番目の静的初期化ブロックは独自の静的メソッドを必要としないため、完全に並列化できます。

4

1 に答える 1