为什么Firebase Java SDK设置后无法终止? [英] Why Firebase Java SDK can't terminate after set?
问题描述
我想构建一个简单的应用程序,以将Firebase数据库中的某些键设置为某个值.因为它是异步的,所以我创建了CountDownLatch
并等待它完成,但是它从未完成.
I want to build simple app that sets some key in a firebase database to some value. Because it is async, I create CountDownLatch
and wait for it to complete, but it never completes.
这是我的代码:
package me.ibrohim.adler;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.tasks.OnCompleteListener;
import com.google.firebase.tasks.Task;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
public class Main {
public static void main(String [] args) throws InterruptedException {
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream("/home/ibrohim/.adler/adminsdk.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://[my app].firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serviceAccount != null) try {
serviceAccount.close();
} catch (IOException e) {
e.printStackTrace();
}
}
CountDownLatch done = new CountDownLatch(1);
// new Thread(() -> {
// try {
// Thread.sleep(1000);
// done.countDown();
// }
// catch (Exception e){
// System.err.println(e);
// }
// }).start();
FirebaseDatabase
.getInstance()
.getReference("[some path]")
.setValue("[some value]")
.addOnCompleteListener(task -> done.countDown());
done.await();
}
}
推荐答案
我刚刚在IntelliJ中运行了这段代码:
I just ran this code in IntelliJ:
CountDownLatch done = new CountDownLatch(1);
database.getReference("45253891").setValue("[some value]")
.addOnCompleteListener(task -> done.countDown());
done.await();
它运行起来没有任何问题. (请参见结果此处)
And it ran without any problem. (see the result here)
我不确定您系统中正在发生什么.您确定能打到setValue()
电话吗?
I'm not sure what's going on in your system. Are you sure you reach the setValue()
call?
更新:Doug Stevenson在评论中展示了如何确保完成后退出JVM:
Update: in the comments Doug Stevenson shows how you can ensure the JVM exits when you're done:
我通常在等待之后添加
System.exit(0)
,以在知道完成后强制停止操作.
I typically add
System.exit(0)
after the await to force things to stop when I know they're done.
因此,它使用CountDownLatch
或类似的同步原语,但在其后添加System.exit(0)
.
So this uses a CountDownLatch
or similar synchronization primitive like above, but then adds a System.exit(0)
after it.
这篇关于为什么Firebase Java SDK设置后无法终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!