From 5b2909d7d69e56ad5c429a99cd9cbb79d415bfc7 Mon Sep 17 00:00:00 2001 From: games647 Date: Mon, 18 Jan 2016 20:34:49 +0100 Subject: [PATCH] Wait for unfinished tasks of the Bukkit scheduler before closing the executor service --- src/main/java/fr/xephi/authme/AuthMe.java | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 15e861bda..51bac6980 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -74,9 +74,11 @@ import java.net.URL; import java.util.Calendar; import java.util.Collection; import java.util.Date; +import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -535,6 +537,40 @@ public class AuthMe extends JavaPlugin { moduleManager.unloadModules(); } + List pendingTasks = getServer().getScheduler().getPendingTasks(); + for (Iterator iterator = pendingTasks.iterator(); iterator.hasNext();) { + BukkitTask pendingTask = iterator.next(); + if (pendingTask.getOwner().equals(this) || pendingTask.isSync()) { + //remove all unrelevant tasks + iterator.remove(); + } + } + + getLogger().log(Level.INFO, "Waiting for {0} tasks to finish", pendingTasks.size()); + int progress = 0; + try { + for (BukkitTask pendingTask : pendingTasks) { + int maxTries = 5; + int taskId = pendingTask.getTaskId(); + while (getServer().getScheduler().isCurrentlyRunning(taskId)) { + if (maxTries <= 0) { + getLogger().log(Level.INFO, "Async task {0} times out after to many tries", taskId); + break; + } + + //one second + Thread.sleep(1000); + maxTries--; + } + + progress++; + getLogger().log(Level.INFO, "Progress: {0} / {1}", new Object[]{progress, pendingTasks.size()}); + } + } catch (InterruptedException interruptedException) { + + } + + // Close the database if (database != null) { database.close();