Skip to content

Instantly share code, notes, and snippets.

@jarcode-foss
Last active January 19, 2016 22:06
Show Gist options
  • Save jarcode-foss/7594ffdf98466724ca5d to your computer and use it in GitHub Desktop.
Save jarcode-foss/7594ffdf98466724ca5d to your computer and use it in GitHub Desktop.
private final Object WAIT_LOCK = new Object();
private int taskCount = 0;
@FunctionalInterface
public interface SafeAsyncTask<E extends Throwable> {
public void run() throws E;
}
public void safeAsyncTask(final SafeAsyncTask task) {
Bukkit.getScheduler().runTaskAsynchronously(PLUGIN, () -> {
synchronized (WAIT_LOCK) {
++taskCount;
}
try {
task.run();
}
catch (Throwable e) {
e.printStackTrace();
}
finally {
synchronized (WAIT_LOCK) {
--taskCount;
WAIT_LOCK.notifyAll();
}
}
});
}
public void waitForTasks() {
try {
synchronized (WAIT_LOCK) {
while (taskCount > 0) {
WAIT_LOCK.wait();
}
}
}
catch (InterruptedException err) {
err.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment