I have a Google app engine + firebase database backend architecture. I am writing a servlet, which should get some values from database, make calculations and build a response with this values. The problem is that onDataChange() method is called asynchronously. At first I'd introduce my code and then continue:
//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();
}
}
Now the question, recently I have read that only one servlet instance is created to respond to http requests. That is why I cant use synchronized(this) as it will stop synchronized threads of all client responses the server gets (i need to stop only 1 main thread, the main thread of only one request). How to get rid of the method asynchronicity properly?