Skip to content

Commit

Permalink
- ItemStackCapInitTask 边界情况异常修复。
Browse files Browse the repository at this point in the history
  • Loading branch information
KasumiNova committed Oct 23, 2024
1 parent 122f9b9 commit e0e9440
Showing 1 changed file with 53 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,84 @@
import github.kasuminova.stellarcore.mixin.util.StellarItemStack;
import net.minecraft.item.ItemStack;

import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("DataFlowIssue")
public class ItemStackCapInitTask implements Runnable {

private final StellarItemStack target;
private volatile boolean done = false;

private final AtomicBoolean done = new AtomicBoolean(false);
private final AtomicBoolean joined = new AtomicBoolean(false);

private volatile Thread working = null;
private volatile Thread joining = null;

public ItemStackCapInitTask(final ItemStack target) {
this.target = (StellarItemStack) (Object) target;
}

@Override
public synchronized void run() {
if (done) {
if (done.get()) {
return;
}
working = Thread.currentThread();

try {
target.stellar_core$initCap();
} catch (Throwable e) {
StellarLog.LOG.warn("[StellarCore-ItemStackCapInitTask] Failed to execute capability init task!", e);
}
done = true;

working = null;
done.set(true);
}

public boolean isDone() {
return done;
return done.get();
}

public void join() {
if (!done) {
public boolean join() {
if (joined.get()) {
return true;
}

final Thread current = Thread.currentThread();
// Recursion check.
if (this.joining == current || this.working == current) {
return false;
}

// Lock the target instead of the task itself.
synchronized (this) {
// Recursion check.
if (this.joining == current || this.working == current) {
return false;
}
// Wait for another thread finish.
awaitJoinComplete();
// Set the joining thread.
this.joining = current;
}

if (!done.get()) {
run();
}
target.stellar_core$joinCapInit();
if (!joined.get()) {
target.stellar_core$joinCapInit();
joined.set(true);
}

this.joining = null;
return true;
}

private void awaitJoinComplete() {
// Wait for the task to finish.
while (this.joining != null) {
Thread.yield();
}
}

}

0 comments on commit e0e9440

Please sign in to comment.