2

私はGoogleアプリエンジン+ firebaseデータベースバックエンドアーキテクチャを持っています。私はサーブレットを作成しています。サーブレットはデータベースから値を取得し、計算してこの値で応答を作成します。問題は、onDataChange()メソッドが非同期に呼び出されることです。最初は、私は私のコードを紹介し、次に進みたい:質問Googleアプリエンジン標準+ Firebaseデータベース

//Here I initialize a listener that would be called when the onDataChange() 
//method is finished to make the code synchronous. 
    responseReadyListener = new ResponseReadyListener() { 
      @Override 
      public void onResponseReady() { 
       responseReady[0] = true; 
       synchronized (MyServlet.this) { 
        MyServlet.this.notify(); 
       } 
      } 
     }; 
     ref.addListenerForSingleValueEvent(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
        //notify the main thread that the response can be sent 
        responseReadyListener.onResponseReady(); 
       } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 

      } 
     }); 
     //the loop that stops the main thread until onDataChange() finishes 
     while (!responseReady[0]) { 
      try { 
       synchronized (this) { 
        if (!responseReady[0]) { 
         this.wait(); 
        } 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 

、最近私は1つのサーブレットインスタンスがHTTP要求に応答するために作成されていることを読みました。これは、サーバーが取得するすべてのクライアント応答の同期されたスレッドを停止するためです(私は1つのメインスレッド、つまり1つの要求のメインスレッドのみを停止する必要があります)。メソッドの非同期性を正しく取り除く方法

+0

多分このスレッドがあなたにいくつかの入力https://stackoverflow.com/questions/42467781/how-would-i-return-a-firebase-custom-token-を与えることができますカスタムトークン生成の場合は/ 42473134#42473134 –

答えて

0

私は自分自身にいくつかの研究を行い、クラスCountDownLatchを見つけました。 ExecutorServiceのような他のクラスは、実行可能なインスタンスを取得できないとき(あなたがそうではなく、apiがスレッドを作成するとき)、まさに私のケースです。ここではその使い方の例です:

final CountDownLatch synchronizer = new CountDownLatch(N/*this number represents the nubmer of threads that should finish before continuation*/); 

    ref.addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
       //another thread, countDown() says CountDownLatch that 
       //one thread has finished its work (N = N - 1). 
       synchronizer.countDown(); 
      } 
     } 
    }); 

    try { 
     //main thread. Await() method stops the thread until countDown() is 
     //called N times, then execution continues. 
     synchronizer.await(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 
関連する問題