Skip to content

Commit eaadb46

Browse files
committed
make clientUUIDCache thread-safe
adjust debug method params
1 parent f55712c commit eaadb46

20 files changed

Lines changed: 107 additions & 64 deletions

File tree

src/main/java/de/srendi/advancedperipherals/AdvancedPeripherals.java

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -74,19 +74,22 @@ public static MessageDigest getFingerprintMessageDigest() {
7474
return fingerprintMessageDigest;
7575
}
7676

77-
public static void debug(String message) {
78-
if (APConfig.GENERAL_CONFIG.enableDebugMode.get())
79-
LOGGER.info("[DEBUG] {}", message);
77+
public static void debug(String message, Object... params) {
78+
if (APConfig.GENERAL_CONFIG.enableDebugMode.get()) {
79+
LOGGER.info("[DEBUG] " + message, params);
80+
}
8081
}
8182

82-
public static void debug(String message, Level level) {
83-
if (APConfig.GENERAL_CONFIG.enableDebugMode.get())
84-
LOGGER.log(level, "[DEBUG] {}", message);
83+
public static void debug(Level level, String message, Object... params) {
84+
if (APConfig.GENERAL_CONFIG.enableDebugMode.get()) {
85+
LOGGER.log(level, "[DEBUG] " + message, params);
86+
}
8587
}
8688

8789
public static void debug(String message, Throwable throwable) {
88-
if (APConfig.GENERAL_CONFIG.enableDebugMode.get())
90+
if (APConfig.GENERAL_CONFIG.enableDebugMode.get()) {
8991
LOGGER.error("[DEBUG] " + message, throwable);
92+
}
9093
}
9194

9295
public static void exception(String message, Throwable throwable) {

src/main/java/de/srendi/advancedperipherals/client/ClientEventSubscriber.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import net.neoforged.api.distmarker.Dist;
1111
import net.neoforged.bus.api.SubscribeEvent;
1212
import net.neoforged.fml.common.EventBusSubscriber;
13+
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
1314
import net.neoforged.neoforge.client.event.ClientTickEvent;
1415
import net.neoforged.neoforge.client.event.InputEvent;
1516
import net.neoforged.neoforge.client.event.MovementInputUpdateEvent;
@@ -24,6 +25,11 @@ public class ClientEventSubscriber {
2425
private static int lastHeight = 0;
2526
private static double lastScale = 0;
2627

28+
@SubscribeEvent
29+
public static void onClientLoggingIn(ClientPlayerNetworkEvent.LoggingIn event) {
30+
ClientUUIDCache.reset();
31+
}
32+
2733
@SubscribeEvent
2834
public static void preClientTick(ClientTickEvent.Pre event) {
2935
Minecraft minecraft = Minecraft.getInstance();

src/main/java/de/srendi/advancedperipherals/client/ClientUUIDCache.java

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22

33
import de.srendi.advancedperipherals.AdvancedPeripherals;
44
import de.srendi.advancedperipherals.common.network.toserver.RetrieveUsernamePacket;
5+
import de.srendi.advancedperipherals.common.util.LRUCache;
56
import net.minecraft.world.item.ItemStack;
67
import net.minecraft.world.item.TooltipFlag;
78
import net.minecraft.world.level.Level;
89
import net.neoforged.neoforge.network.PacketDistributor;
910
import org.jetbrains.annotations.Nullable;
1011

11-
import java.util.HashMap;
1212
import java.util.List;
13+
import java.util.Map;
1314
import java.util.UUID;
15+
import java.util.concurrent.ConcurrentHashMap;
16+
import java.util.concurrent.locks.ReadWriteLock;
17+
import java.util.concurrent.locks.ReentrantReadWriteLock;
1418

1519
/**
1620
* Used for client side messages where we don't have a username, only a UUID
@@ -20,22 +24,53 @@
2024
*/
2125
public class ClientUUIDCache {
2226

23-
private static final HashMap<UUID, String> CACHE = new HashMap<>();
27+
private static final ReadWriteLock LOCK = new ReentrantReadWriteLock();
28+
private static final LRUCache<UUID, String> CACHE = new LRUCache<>(128);
29+
private static final Map<UUID, Long> QUERYING = new ConcurrentHashMap<>();
2430

2531
private ClientUUIDCache() { }
2632

2733
@Nullable
2834
public static String getUsername(UUID uuid) {
29-
if (CACHE.containsKey(uuid))
30-
return CACHE.get(uuid);
31-
32-
PacketDistributor.sendToServer(new RetrieveUsernamePacket(uuid));
35+
String username;
36+
LOCK.readLock().lock();
37+
try {
38+
username = CACHE.get(uuid);
39+
} finally {
40+
LOCK.readLock().unlock();
41+
}
42+
if (username != null) {
43+
return username;
44+
}
45+
QUERYING.compute(uuid, (uuid2, timeout) -> {
46+
long now = System.currentTimeMillis();
47+
if (timeout != null && timeout >= now) {
48+
return timeout;
49+
}
50+
PacketDistributor.sendToServer(new RetrieveUsernamePacket(uuid2));
51+
return now + 10 * 1000;
52+
});
3353
return null;
3454
}
3555

3656
public static void putUsername(UUID uuid, String username) {
37-
CACHE.put(uuid, username);
38-
AdvancedPeripherals.debug(String.format("Putting username %s with uuid %s into cache", username, uuid));
57+
AdvancedPeripherals.debug("Putting username {} with uuid {} into cache", username, uuid);
58+
LOCK.writeLock().lock();
59+
try {
60+
CACHE.put(uuid, username);
61+
} finally {
62+
LOCK.writeLock().unlock();
63+
}
64+
QUERYING.remove(uuid);
3965
}
4066

67+
public static void reset() {
68+
LOCK.writeLock().lock();
69+
try {
70+
CACHE.clear();
71+
} finally {
72+
LOCK.writeLock().unlock();
73+
}
74+
QUERYING.clear();
75+
}
4176
}

src/main/java/de/srendi/advancedperipherals/client/screens/KeyboardScreen.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,8 @@ private void grabMouse() {
228228
}
229229
Window window = this.minecraft.getWindow();
230230
synchronized (this.lastPosLock) {
231-
this.lastX = window.getScreenWidth() / 2;
232-
this.lastY = window.getScreenHeight() / 2;
231+
this.lastX = window.getScreenWidth() / 2.0;
232+
this.lastY = window.getScreenHeight() / 2.0;
233233
InputConstants.grabOrReleaseMouse(window.getWindow(), InputConstants.CURSOR_DISABLED, this.lastX, this.lastY);
234234
}
235235
this.mouseState = MouseState.CAPTURE;
@@ -245,8 +245,8 @@ private void releaseMouse() {
245245
}
246246
Window window = this.minecraft.getWindow();
247247
synchronized (this.lastPosLock) {
248-
this.lastX = window.getScreenWidth() / 2;
249-
this.lastY = window.getScreenHeight() / 2;
248+
this.lastX = window.getScreenWidth() / 2.0;
249+
this.lastY = window.getScreenHeight() / 2.0;
250250
InputConstants.grabOrReleaseMouse(window.getWindow(), InputConstants.CURSOR_NORMAL, this.lastX, this.lastY);
251251
}
252252
this.mouseState = MouseState.RELEASED;

src/main/java/de/srendi/advancedperipherals/common/addons/appliedenergistics/AEApi.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ public static <T extends AEKey> Map<String, Object> parseAeStack(Pair<Long, T> s
360360
if (APAddon.APP_MEKANISTICS.isLoaded() && (stack.right() instanceof MekanismKey gasKey))
361361
return parseChemStack(Pair.of(stack.left(), gasKey), service);
362362

363-
AdvancedPeripherals.debug("Could not create table from unknown stack " + stack.right().getClass() + " - Report this to the maintainer of ap", org.apache.logging.log4j.Level.WARN);
363+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.WARN, "Could not create table from unknown stack {} - Report this to the maintainer of ap", stack.right().getClass());
364364
return null;
365365
}
366366

@@ -372,7 +372,7 @@ public static Map<String, Object> parseGenericStack(GenericStack stack) {
372372
if (stack.what() instanceof AEFluidKey aeFluidKey)
373373
return parseFluidStack(Pair.of(stack.amount(), aeFluidKey), null);
374374

375-
AdvancedPeripherals.debug("Could not create table from unknown stack " + stack.getClass() + " - Report this to the maintainer of ap", org.apache.logging.log4j.Level.WARN);
375+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.WARN, "Could not create table from unknown stack {} - Report this to the maintainer of ap", stack.getClass());
376376
return null;
377377
}
378378

src/main/java/de/srendi/advancedperipherals/common/addons/appliedenergistics/AECraftJob.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,14 +218,14 @@ public void maybeCraft() {
218218
try {
219219
job = futureJob.get();
220220
} catch (ExecutionException | InterruptedException ex) {
221-
AdvancedPeripherals.debug("Tried to get job, but job calculation is not done. Should be done.", org.apache.logging.log4j.Level.ERROR);
221+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.ERROR, "Tried to get job, but job calculation is not done. Should be done.");
222222
ex.printStackTrace();
223223
fireEvent(true, StatusConstants.UNKNOWN_ERROR);
224224
return;
225225
}
226226

227227
if (job == null) {
228-
AdvancedPeripherals.debug("Job is null, should not be null.", org.apache.logging.log4j.Level.ERROR);
228+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.ERROR, "Job is null, should not be null.");
229229
fireEvent(true, StatusConstants.UNKNOWN_ERROR);
230230
return;
231231
}
@@ -300,7 +300,7 @@ private void prepareCPUAndStatus(ICraftingService service) {
300300
}
301301
}
302302
}
303-
AdvancedPeripherals.debug("Could not find CPU or job link even after job started", org.apache.logging.log4j.Level.WARN);
303+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.ERROR, "Could not find CPU or job link even after job started");
304304
}
305305

306306
private CraftingJobStatus getJobStatus() {

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ public final Object getResearch() throws LuaException {
217217
try {
218218
result.put(branch.toString(), MineColonies.getResearch(branch, globalTree.getPrimaryResearch(branch), colony));
219219
} catch (CommandSyntaxException ex) {
220-
AdvancedPeripherals.debug("Error getting research for branch " + branch + ": " + ex.getMessage(), org.apache.logging.log4j.Level.WARN);
220+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.WARN, "Error getting research for branch {}: {}", branch, ex.getMessage());
221221
ex.printStackTrace();
222222
}
223223
}

src/main/java/de/srendi/advancedperipherals/common/addons/refinedstorage/RSApi.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,7 @@ public static Map<String, Object> getObjectFromResourceKey(@NotNull ResourceKey
581581
}
582582
return getObjectFromChemicalResource(new ResourceAmount(resource, count), autocraftingComponent);
583583
}
584-
AdvancedPeripherals.debug("Could not create table from unknown resource " + resource.getClass() + " - Report this to the maintainer of ap", Level.WARN);
584+
AdvancedPeripherals.debug(Level.WARN, "Could not create table from unknown resource {} - Report this to the maintainer of ap", resource.getClass());
585585
return Collections.emptyMap();
586586
}
587587

@@ -601,7 +601,7 @@ public static Map<String, Object> getObjectFromResourceAmount(@NotNull ResourceA
601601
if (APAddon.REFINEDSTORAGE_MEKANISM.isLoaded() && resourceAmount.resource() instanceof ChemicalResource) {
602602
return getObjectFromChemicalResource(resourceAmount, autocraftingComponent);
603603
}
604-
AdvancedPeripherals.debug("Could not create table from unknown resourceAmount " + resourceAmount.getClass() + " - Report this to the maintainer of ap", Level.WARN);
604+
AdvancedPeripherals.debug(Level.WARN, "Could not create table from unknown resourceAmount {} - Report this to the maintainer of ap", resourceAmount.getClass());
605605
return Collections.emptyMap();
606606
}
607607

src/main/java/de/srendi/advancedperipherals/common/addons/refinedstorage/RSCraftJob.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ protected void maybeCraft() {
172172

173173
// TODO: I currently don't exactly know when the optional can be empty after the future is done. So I need to evaluate this.
174174
if (optionalPreview.isEmpty()) {
175-
AdvancedPeripherals.debug("preview optional is empty.", org.apache.logging.log4j.Level.ERROR);
175+
AdvancedPeripherals.debug(org.apache.logging.log4j.Level.ERROR, "preview optional is empty.");
176176
fireEvent(true, StatusConstants.UNKNOWN_ERROR);
177177
return;
178178
}

src/main/java/de/srendi/advancedperipherals/common/entity/TurtleEnderPearl.java

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,6 @@ public void setCallback(Consumer<TurtleEnderPearl> callback) {
6464
this.callback = callback;
6565
}
6666

67-
@Nullable
68-
private ServerComputer getServerComputer() {
69-
if (this.turtle instanceof TurtleBrain brain) {
70-
return brain.getOwner().createServerComputer();
71-
}
72-
return null;
73-
}
74-
7567
@Override
7668
public void readAdditionalSaveData(CompoundTag storage) {}
7769

@@ -106,7 +98,7 @@ public void tick() {
10698
this.life = -1;
10799
this.setDeltaMovement(Vec3.ZERO);
108100
this.moveTo(Vec3.atCenterOf(this.blockPosition()));
109-
AdvancedPeripherals.debug("Turtle Ender Pearl stabled: " + this.toString());
101+
AdvancedPeripherals.debug("Turtle Ender Pearl stabled: {}", this.toString());
110102
if (this.callback != null) {
111103
this.callback.accept(this);
112104
}
@@ -170,7 +162,7 @@ public Entity changeDimension(@NotNull DimensionTransition transition) {
170162
Entity newEntity = super.changeDimension(transition);
171163
this.changedDim = newEntity != null;
172164
if (newEntity instanceof TurtleEnderPearl newPearl) {
173-
AdvancedPeripherals.debug("Turtle Ender Pearl crossed to dimension " + newLevel.dimension());
165+
AdvancedPeripherals.debug("Turtle Ender Pearl crossed to dimension {}", newLevel.dimension());
174166
newPearl.spawnPos = newPearl.blockPosition();
175167
ChunkManager.get(newLevel.getServer()).addForceChunk(newLevel, newPearl.getUUID(), newPearl.chunkPosition());
176168
if (newLevel.dimension() == Level.END) {
@@ -183,12 +175,12 @@ public Entity changeDimension(@NotNull DimensionTransition transition) {
183175
break;
184176
}
185177
}
186-
AdvancedPeripherals.debug("Turtle Ender Pearl lowest Y: " + lowestY);
178+
AdvancedPeripherals.debug("Turtle Ender Pearl lowest Y: {}", lowestY);
187179
for (int y = lowestY; y <= maxHeight; y++) {
188180
BlockPos pos = newPearl.spawnPos.atY(y);
189181
List<TurtleEnderPearl> pearlList = newLevel.getEntities(APEntities.TURTLE_ENDER_PEARL.get(), new AABB(pos), entity -> true);
190182
if (pearlList.isEmpty()) {
191-
AdvancedPeripherals.debug("Turtle Ender Pearl moved to " + pos);
183+
AdvancedPeripherals.debug("Turtle Ender Pearl moved to {}", pos);
192184
newPearl.moveTo(Vec3.atCenterOf(pos));
193185
break;
194186
}

0 commit comments

Comments
 (0)