Skip to content

Instantly share code, notes, and snippets.

@nullexcept1on
Forked from blablubbabc/SomePlugin.java
Created October 8, 2020 20:15
Show Gist options
  • Save nullexcept1on/2f8f74e122680b6e1f297e959dd2b801 to your computer and use it in GitHub Desktop.
Save nullexcept1on/2f8f74e122680b6e1f297e959dd2b801 to your computer and use it in GitHub Desktop.
Waiting for running async bukkit tasks to finish inside onDisable()
// 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