问题定义:-
我需要在insert some values into Database
所有任务ExecutorService
完成后立即执行那里的工作。换句话说,我insert into database
只能在所有任务都完成执行那里的作业时,因为我需要插入到数据库中的东西,取决于完成那里任务的所有线程。
那么我如何检查所有任务是否ExecutorService
已完成执行然后开始插入数据库。
下面是我使用创建任务的代码ThreadPoolExecutor
。
executorService = new ThreadPoolExecutor(
noOfThreads,
noOfThreads,
500L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(noOfThreads),
new ThreadPoolExecutor.CallerRunsPolicy()
);
// Running for particular duration of time
while(System.currentTimeMillis() <= endTime) {
Command newCommand = getNextCommand();
Task nextRunnable = new Task(newCommand, existId, newId);
executorService.submit(nextRunnable); // Submit it for execution
}
/*
Previously I was inserting into database here, but it was wrong as it might be
possible that some threads are still in progress. And If I am inserting right here
into database, then some information I will be loosing for sure. So how can I check
whether all the tasks have finished executing and then I can insert into database.
*/
executorService.shutdown();
if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS)) {
executorService.shutdownNow();
}
我将用于插入的代码如下 -
// Inserting into Database when all the task have finished executing, currently I
for (Entry<Integer, LinkedHashMap<Integer, String>> entry : GUID_ID_MAPPING.entrySet()) {
pstatement = db_connection.prepareStatement(LnPConstants.UPSERT_SQL);
pstatement.setInt(1, entry.getKey());
pstatement.setString(2, entry.getValue().get(LnPConstants.CGUID_ID));
pstatement.setString(3, entry.getValue().get(LnPConstants.PGUID_ID));
pstatement.executeUpdate();
}
所以我需要在所有任务完成执行后将这个 for 循环放在某个地方。
更新:-
所以像这样的东西-
executorService.shutdown();
if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS)) {
executorService.shutdownNow();
}
// Now Insert into Database when all the task have finished executing
for (Entry<Integer, LinkedHashMap<Integer, String>> entry : GUID_ID_MAPPING.entrySet()) {
pstatement = db_connection.prepareStatement(PDSLnPConstants.UPSERT_SQL);
pstatement.setInt(1, entry.getKey());
pstatement.setString(2, entry.getValue().get(PDSLnPConstants.CGUID_ID));
pstatement.setString(3, entry.getValue().get(PDSLnPConstants.PGUID_ID));
pstatement.executeUpdate();
}