使用CountDownLatch.await()

时间:2019-04-23 04:28:48

标签: java android multithreading firebase

正如标题所说,我完全不知道为什么听众没有开火。这是相关代码:

Log.i(Reference.LOG_TAG, "Loading menu from firebase");
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<List<Category>> output = new AtomicReference<>();
// this line does not fix the issue
// menuBaseRef.keepSynced(true);
menuBaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        Log.d(Reference.LOG_TAG, "Invoking onDataChange for menu loading");
        List<Category> categories = new ArrayList<>();
        // irrelevant, code to load categories
        Log.i(Reference.LOG_TAG, "Done loading, releasing latch");
        output.set(categories);
        latch.countDown();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.e(Reference.LOG_TAG, "Error loading menu \"" + databaseError.toString() + "\"");
        latch.countDown();
    }
});
try {
    Log.i(Reference.LOG_TAG, "Latching while menu loads");
    latch.await(); // this makes the listener not fire
    Log.i(Reference.LOG_TAG, "Menu latch released");
    return output.get();
} catch (InterruptedException e) {
    Log.e(Reference.LOG_TAG, "Latch interrupted while waiting for menu to load");
    return null;
}

按原样运行此代码将导致latch.await()永远无法完成。日志中最后一条消息是“菜单加载时闩锁”,看不到“调用菜单加载onDataChange”。 一旦删除latch.await(),就会按预期方式打印“正在调用onDataChange进行菜单加载”消息。

我尝试过menuBaseRef.keepSynced(true),但是它什么也没做。

对于为什么会发生这种情况的任何见解都会受到赞赏。

0 个答案:

没有答案