Skip to content

Commit

Permalink
Improve error handling in LazyDispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
Pyrofab committed Jun 15, 2021
1 parent ff75039 commit 0002950
Showing 1 changed file with 22 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,55 +25,59 @@
import org.jetbrains.annotations.ApiStatus;

public abstract class LazyDispatcher {
private volatile boolean requiresInitialization = true;
private volatile boolean loading = false;
private volatile State state = State.UNLOADED;
private final String likelyInitTrigger;

protected LazyDispatcher(String likelyInitTrigger) {
this.likelyInitTrigger = likelyInitTrigger;
}

public void ensureInitialized() {
if (this.requiresInitialization) {
if (this.state == State.ERRED) {
throw new IllegalStateException("Initialization failed, check the log above for likely causes");
} else if (this.state != State.LOADED) {
synchronized (this) {
if (this.requiresInitialization) {
if (this.loading) {
this.onCircularLoading();
} else {
this.loading = true;
if (this.state == State.LOADING) {
this.onCircularLoading();
} else if (this.state == State.UNLOADED) {
this.state = State.LOADING;

try {
this.init();
} finally {
this.loading = false;
}

this.requiresInitialization = false;
try {
this.init();
this.state = State.LOADED;
this.postInit();
} catch (Throwable t) {
this.state = State.ERRED;
ComponentsInternals.LOGGER.fatal("[Cardinal Components API] Initialization failed: ", t);
throw t;
}
}
}
}
}

protected void onCircularLoading() {
throw new IllegalStateException("Circular loading issue, a mod is probably " + this.likelyInitTrigger + " in the wrong place");
throw new IllegalStateException("Circular loading issue, a mod is probably " + this.likelyInitTrigger + " in the wrong place");
}

protected boolean requiresInitialization() {
return this.requiresInitialization;
return this.state == State.UNLOADED;
}

@ApiStatus.OverrideOnly
protected abstract void init();

public void checkLoading(Class<?> ownerClass, String methodName) {
if (!this.loading) {
if (this.state != State.LOADING) {
throw new IllegalStateException(ownerClass.getSimpleName() + "#" + methodName + " called at the wrong time");
}
}

protected void postInit() {
// NO-OP
}

enum State {
UNLOADED, LOADING, LOADED, ERRED
}
}

0 comments on commit 0002950

Please sign in to comment.