Skip to content

Commit

Permalink
fix atomics causing aggressive cpu cache invalidation
Browse files Browse the repository at this point in the history
  • Loading branch information
FalsePattern committed Jan 10, 2024
1 parent 6a611df commit 507a3a9
Showing 1 changed file with 11 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
import net.minecraft.util.LongHashMap;
import net.minecraft.world.World;

import cpw.mods.fml.common.FMLCommonHandler;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
Expand All @@ -41,12 +44,15 @@
public abstract class ChunkProviderClientMixin {
@Unique
private volatile AtomicLong ft$writeCount;
@Unique
private volatile ThreadLocal<Boolean> ft$isClientThread;

@Inject(method = "<init>",
at = @At("RETURN"),
require = 1)
private void initMutex(World p_i1184_1_, CallbackInfo ci) {
ft$writeCount = new AtomicLong();
ft$isClientThread = ThreadLocal.withInitial(() -> Thread.currentThread().getName().equals("Client thread"));
}

@Redirect(method = "unloadChunk",
Expand Down Expand Up @@ -80,6 +86,11 @@ private void threadSafeLoad(LongHashMap instance, long id, Object value) {
target = "Lnet/minecraft/util/LongHashMap;getValueByKey(J)Ljava/lang/Object;"),
require = 1)
private Object threadSafeGet(LongHashMap instance, long id) {
if (ft$isClientThread.get())
return instance.getValueByKey(id);
try {
return instance.getValueByKey(id);
} catch (ArrayIndexOutOfBoundsException ignored) {}
Object result = null;
long expectedWriteCount;
boolean retry;
Expand Down

1 comment on commit 507a3a9

@embeddedt
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storing the client thread as a field and doing Thread.currentThread() == clientThread should be a lot faster. It's reasonable to assume the client thread doesn't change for the lifetime of the chunk provider.

Please sign in to comment.