java - Google app engine standard + Firebase database -
i have google app engine + firebase database backend architecture. writing servlet, should values database, make calculations , build response values. problem ondatachange() method called asynchronously. @ first i'd introduce code , continue:
//here initialize listener called when ondatachange() //method finished make 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 main thread response can sent responsereadylistener.onresponseready(); } } @override public void oncancelled(databaseerror databaseerror) { } }); //the loop stops main thread until ondatachange() finishes while (!responseready[0]) { try { synchronized (this) { if (!responseready[0]) { this.wait(); } } } catch (interruptedexception e) { e.printstacktrace(); } } now question, have read 1 servlet instance created respond http requests. why cant use synchronized(this) stop synchronized threads of client responses server gets (i need stop 1 main thread, main thread of 1 request). how rid of method asynchronicity properly?
i've made research on own , found class countdownlatch. other classes executorservice not suitable when cannot runnable instance (when not api creates thread) case. here example of usage:
final countdownlatch synchronizer = new countdownlatch(n/*this number represents nubmer of threads should finish before continuation*/); ref.addlistenerforsinglevalueevent(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { //another thread, countdown() says countdownlatch //one thread has finished work (n = n - 1). synchronizer.countdown(); } } }); try { //main thread. await() method stops thread until countdown() //called n times, execution continues. synchronizer.await(); } catch (interruptedexception e) { e.printstacktrace(); } }
Comments
Post a Comment