-
-
Save nullexcept1on/2f8f74e122680b6e1f297e959dd2b801 to your computer and use it in GitHub Desktop.
Waiting for running async bukkit tasks to finish inside onDisable()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inside the plugin class | |
private static final long ASYNC_TASKS_TIMEOUT_SECONDS = 10; | |
@Override | |
public void onDisable() { | |
// wait for async tasks to complete: | |
final long asyncTasksTimeoutMillis = ASYNC_TASKS_TIMEOUT_SECONDS * 1000; | |
final long asyncTasksStart = System.currentTimeMillis(); | |
boolean asyncTasksTimeout = false; | |
while (this.getActiveAsyncTasks() > 0) { | |
try { | |
Thread.sleep(5); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
// after timeout disable anyways..: | |
if (System.currentTimeMillis() - asyncTasksStart > asyncTasksTimeoutMillis) { | |
asyncTasksTimeout = true; | |
this.getLogger().warning("Waited " + ASYNC_TASKS_TIMEOUT_SECONDS + " seconds for " + this.getActiveAsyncTasks() | |
+ " remaining async tasks to complete. Disabling now anyways.."); | |
break; | |
} | |
} | |
final long asyncTasksTimeWaited = System.currentTimeMillis() - asyncTasksStart; | |
if (!asyncTasksTimeout && asyncTasksTimeWaited > 1) { | |
this.getLogger().info("Waited " + asyncTasksTimeWaited + " ms for async tasks to finish."); | |
} | |
} | |
private int getActiveAsyncTasks() { | |
int workers = 0; | |
for (BukkitWorker worker : Bukkit.getScheduler().getActiveWorkers()) { | |
if (worker.getOwner().equals(this)) { | |
workers++; | |
} | |
} | |
return workers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment