我在App Engine项目中有一个DeferredTask,用于异步地将数据导入Firestore,如下所示:
public void run() {
FirestoreOptions options = ...
try (Firestore db = options.getService()) {
CollectionReference placesCollection = db.collection("MyCollection");
Map<String, Object> data = new HashMap<>();
data.put("key", "value");
DocumentReference doc = placesCollection.document("MyId");
doc.set(data)
} catch (Exception e) {
...
}
}
代码运行没有错误,但是方法结束后,我在控制台中看到一个异常,并且没有数据写入我的集合:
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@7be031d1 rejected from java.util.concurrent.ScheduledThreadPoolExecutor@6808a2d4[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:326)
at java.util.concurrent.ScheduledThreadPoolExecutor.schedule(ScheduledThreadPoolExecutor.java:533)
如果我等待写入完成,则看不到异常:
doc.set(data).get(); // block for write to complete
是我的Firestore连接由于超出try-with-resources范围而关闭,还是只需要等待set()返回的ApiFuture完成的问题?我认为异步Firestore编写背后的想法是,您可以将它们拉开序幕,而且,如果您不在乎完成,则不必等待。