Last active
January 15, 2022 14:58
-
-
Save blablubbabc/e884c114484f34cae316c48290b21d8e 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(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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really nice! But is it really necessary to run it every 5 milliseconds? Surely you could let the main thread sleep longer than that.