Skip to content

Commit

Permalink
fix: fix a possible NPE in chunk service
Browse files Browse the repository at this point in the history
  • Loading branch information
smartcmd committed Apr 4, 2024
1 parent fd9f438 commit 7deccaf
Showing 1 changed file with 5 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -176,15 +176,16 @@ public CompletableFuture<Chunk> loadChunk(int x, int z) {
if (isChunkLoaded(hashXZ)) {
throw new IllegalStateException("Chunk is already loaded");
}
CompletableFuture<Chunk> future;
// Prevent multiple threads from putting the same chunk into loadingChunks at the same time and wasting computing resources
var presentValue = loadingChunks.putIfAbsent(hashXZ, worldStorage.readChunk(x, z, DimensionInfo.OVERWORLD)
var presentValue = loadingChunks.putIfAbsent(hashXZ, future = worldStorage.readChunk(x, z, DimensionInfo.OVERWORLD)
.exceptionally(t -> {
log.error("Error while reading chunk (" + x + "," + z + ") !", t);
log.error("Error while reading chunk ({},{}) !", x, z, t);
return AllayUnsafeChunk.builder().emptyChunk(x, z, dimension.getDimensionInfo()).toSafeChunk();
})
.thenApplyAsync(this::generateChunkIfNeed, Server.getInstance().getComputeThreadPool())
.exceptionally(t -> {
log.error("Error while generating chunk (" + x + "," + z + ") !", t);
log.error("Error while generating chunk ({},{}) !", x, z, t);
return AllayUnsafeChunk.builder().emptyChunk(x, z, dimension.getDimensionInfo()).toSafeChunk();
})
.thenApply(prepareChunk -> {
Expand All @@ -196,7 +197,7 @@ public CompletableFuture<Chunk> loadChunk(int x, int z) {
})
);
if (presentValue == null) {
return loadingChunks.get(hashXZ);
return future;
} else {
return presentValue;
}
Expand Down

0 comments on commit 7deccaf

Please sign in to comment.