2

I have a server written in Java that can receive a shut down signal while it's listening to, processing, and updating Firebase data. Since the Firebase threads are daemon threads in Java, I wanted to add some delay to the main thread to allow write operations to complete.

My current idea is the latch approach: use some concurrent counter to track pending writing operations, and let the main thread exit when there are none. The counter would get updated in onComplete() callbacks, so I was wondering:

In the Firebase client, when might onComplete() callbacks never get called? Is there reasonable danger of deadlock?

Lucas Cook
  • 193
  • 9

2 Answers2

5

Taken from this google group discussion. This uses a boolean done (an AtomicBoolean for thread safe ops in this case) and a while loop.

import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;

import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

public class Demo {

    public static void main(String[] args) {
        final AtomicBoolean done = new AtomicBoolean(false);
        Firebase ref = new Firebase("https://testjava.firebaseio-demo.com/");
        ref.setValue(new Date().toString(), new Firebase.CompletionListener() {
            @Override
            public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                done.set(true);
            }
        });
        while (!done.get());
    }
}
Kato
  • 40,352
  • 6
  • 119
  • 149
  • This is the kind of approach I'll use. Is there any reason to have a timer as well, in case the `onComplete()` callback never happens? I'm thinking of something like [CountDownLatch.await(long timeout, TimeUnit unit)](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html#await%28long,%20java.util.concurrent.TimeUnit%29). – Lucas Cook Sep 30 '14 at 07:30
  • onComplete should always fire either with an error condition or a result. The only exception to this would be if the server were offline and never came online again, in which case the script may be the least of your worries :) – Kato Sep 30 '14 at 13:55
  • if firebase failed to authenticate, the thread will never stop. I tested by removing the key in the admin console. – Ben Cheng Jan 28 '18 at 10:03
1

I think you should shut down the server in 3 stages:

  1. stop receiving more work
  2. wait for all work to finish
  3. issue a shut down to the daemon thread pool when the working counter is 0.

Using a finally in your writing tasks should ensure onComplete() is always called.

try {
   //write
}
finally {
   callbackObject.onComplete();
}
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • Thanks! By "latch approach", I meant to do what you are recommending. My question is really about the Firebase internals. The writes are performed asynchronously by Firebase, so I'm not able to wrap them in a try block and I'm not sure what exceptions will be thrown. – Lucas Cook Sep 29 '14 at 20:02