[英]Google app engine standard + Firebase database
我有一個Google App Engine + Firebase數據庫后端架構。 我正在編寫一個servlet,它應該從數據庫中獲取一些值,進行計算並使用這些值建立響應。 問題在於onDataChange()方法是異步調用的。 首先,我將介紹我的代碼,然后繼續:
//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();
}
}
現在,我最近讀過一個問題,即我只創建了一個servlet實例來響應http請求。 這就是為什么我不能使用synced(this)的原因,因為它將停止服務器獲得的所有客戶端響應的同步線程(我只需要停止1個主線程,僅停止一個請求的主線程)。 如何正確擺脫方法的異步性?
我自己進行了一些研究,發現了一個CountDownLatch
類。 當您無法獲得可運行的實例時(不是由您而是由api創建線程),其他類似ExecutorService的類都不適合,這正是我的情況。 這是一個用法示例:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.