Skip to content

Instantly share code, notes, and snippets.

@blablubbabc
Last active January 15, 2022 14:58
Show Gist options
  • Save blablubbabc/e884c114484f34cae316c48290b21d8e to your computer and use it in GitHub Desktop.
Save blablubbabc/e884c114484f34cae316c48290b21d8e 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(25);
} 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;
}
@hjk321
Copy link

hjk321 commented Oct 17, 2019

Really nice! But is it really necessary to run it every 5 milliseconds? Surely you could let the main thread sleep longer than that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment