IOWorker .java

net.minecraft.world.level.chunk.storage.IOWorker (class): members: regionCacheForBlender, REGION_CACHE_SIZE, shutdownRequested, ThrowingSupplier, Priority.

net.minecraft.world.level.chunk.storageclass277 linescommon9.2 KB

Implements

API Surface (8)

boolean isOldChunkAround(final ChunkPos pos, final int range)
CompletableFuture<Void> store(final ChunkPos pos, final CompoundTag value)
CompletableFuture<Void> store(final ChunkPos pos, final Supplier<CompoundTag> supplier)
CompletableFuture<Optional<CompoundTag>> loadAsync(final ChunkPos pos)
CompletableFuture<Void> synchronize(final boolean flush)
CompletableFuture<Void> scanChunk(final ChunkPos pos, final StreamTagVisitor visitor)
void close()
RegionStorageInfo storageInfo()

Fields & Constants (8)

STORE_EMPTY
LOGGER
REGION_CACHE_SIZE
shutdownRequested
consecutiveExecutor
storage
pendingWrites
regionCacheForBlender

String literals (5)

"IOWorker-"
"DataVersion"
"blending_data"
"Failed to synchronize chunks"
"Failed to close storage"

Full Source

IOWorker.java277 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.chunk.storage;
2
3
import com.mojang.logging.LogUtils;
4
import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
5
import java.io.IOException;
6
import java.nio.file.Path;
7
import java.util.BitSet;
8
import java.util.LinkedHashMap;
9
import java.util.Optional;
10
import java.util.SequencedMap;
11
import java.util.Map.Entry;
12
import java.util.concurrent.CompletableFuture;
13
import java.util.concurrent.atomic.AtomicBoolean;
14
import java.util.function.Function;
15
import java.util.function.Supplier;
16
import net.minecraft.nbt.CompoundTag;
17
import net.minecraft.nbt.IntTag;
18
import net.minecraft.nbt.StreamTagVisitor;
19
import net.minecraft.nbt.visitors.CollectFields;
20
import net.minecraft.nbt.visitors.FieldSelector;
21
import net.minecraft.util.Unit;
22
import net.minecraft.util.Util;
23
import net.minecraft.util.thread.PriorityConsecutiveExecutor;
24
import net.minecraft.util.thread.StrictQueue;
25
import net.minecraft.world.level.ChunkPos;
26
import org.jspecify.annotations.Nullable;
27
import org.slf4j.Logger;
28
29
public class IOWorker implements AutoCloseable, ChunkScanAccess {
30
	public static final Supplier<CompoundTag> STORE_EMPTY = () -> null;
31
	private static final Logger LOGGER = LogUtils.getLogger();
32
	private final AtomicBoolean shutdownRequested = new AtomicBoolean();
33
	private final PriorityConsecutiveExecutor consecutiveExecutor;
34
	private final RegionFileStorage storage;
35
	private final SequencedMap<ChunkPos, IOWorker.PendingStore> pendingWrites = new LinkedHashMap<>();
36
	private final Long2ObjectLinkedOpenHashMap<CompletableFuture<BitSet>> regionCacheForBlender = new Long2ObjectLinkedOpenHashMap<>();
37
	private static final int REGION_CACHE_SIZE = 1024;
38
39
	protected IOWorker(final RegionStorageInfo info, final Path dir, final boolean sync) {
40
		this.storage = new RegionFileStorage(info, dir, sync);
41
		this.consecutiveExecutor = new PriorityConsecutiveExecutor(IOWorker.Priority.values().length, Util.ioPool(), "IOWorker-" + info.type());
42
	}
43
44
	public boolean isOldChunkAround(final ChunkPos pos, final int range) {
45
		ChunkPos from = new ChunkPos(pos.x() - range, pos.z() - range);
46
		ChunkPos to = new ChunkPos(pos.x() + range, pos.z() + range);
47
48
		for (int regionX = from.getRegionX(); regionX <= to.getRegionX(); regionX++) {
49
			for (int regionZ = from.getRegionZ(); regionZ <= to.getRegionZ(); regionZ++) {
50
				BitSet data = this.getOrCreateOldDataForRegion(regionX, regionZ).join();
51
				if (!data.isEmpty()) {
52
					ChunkPos minChunkPos = ChunkPos.minFromRegion(regionX, regionZ);
53
					int startChunkX = Math.max(from.x() - minChunkPos.x(), 0);
54
					int startChunkZ = Math.max(from.z() - minChunkPos.z(), 0);
55
					int endChunkX = Math.min(to.x() - minChunkPos.x(), 31);
56
					int endChunkZ = Math.min(to.z() - minChunkPos.z(), 31);
57
58
					for (int x = startChunkX; x <= endChunkX; x++) {
59
						for (int z = startChunkZ; z <= endChunkZ; z++) {
60
							int chunkIndex = z * 32 + x;
61
							if (data.get(chunkIndex)) {
62
								return true;
63
							}
64
						}
65
					}
66
				}
67
			}
68
		}
69
70
		return false;
71
	}
72
73
	private CompletableFuture<BitSet> getOrCreateOldDataForRegion(final int regionX, final int regionZ) {
74
		long regionPos = ChunkPos.pack(regionX, regionZ);
75
		synchronized (this.regionCacheForBlender) {
76
			CompletableFuture<BitSet> result = this.regionCacheForBlender.getAndMoveToFirst(regionPos);
77
			if (result == null) {
78
				result = this.createOldDataForRegion(regionX, regionZ);
79
				this.regionCacheForBlender.putAndMoveToFirst(regionPos, result);
80
				if (this.regionCacheForBlender.size() > 1024) {
81
					this.regionCacheForBlender.removeLast();
82
				}
83
			}
84
85
			return result;
86
		}
87
	}
88
89
	private CompletableFuture<BitSet> createOldDataForRegion(final int regionX, final int regionZ) {
90
		return CompletableFuture.supplyAsync(() -> {
91
			ChunkPos from = ChunkPos.minFromRegion(regionX, regionZ);
92
			ChunkPos to = ChunkPos.maxFromRegion(regionX, regionZ);
93
			BitSet resultSet = new BitSet();
94
			ChunkPos.rangeClosed(from, to).forEach(pos -> {
95
				CollectFields collectFields = new CollectFields(new FieldSelector(IntTag.TYPE, "DataVersion"), new FieldSelector(CompoundTag.TYPE, "blending_data"));
96
97
				try {
98
					this.scanChunk(pos, collectFields).join();
99
				} catch (Exception e) {
100
					LOGGER.warn("Failed to scan chunk {}", pos, e);
101
					return;
102
				}
103
104
				if (collectFields.getResult() instanceof CompoundTag chunkTag && this.isOldChunk(chunkTag)) {
105
					int chunkIndex = pos.getRegionLocalZ() * 32 + pos.getRegionLocalX();
106
					resultSet.set(chunkIndex);
107
				}
108
			});
109
			return resultSet;
110
		}, Util.backgroundExecutor());
111
	}
112
113
	private boolean isOldChunk(final CompoundTag tag) {
114
		return tag.getIntOr("DataVersion", 0) < 4997 ? true : tag.getCompound("blending_data").isPresent();
115
	}
116
117
	public CompletableFuture<Void> store(final ChunkPos pos, final CompoundTag value) {
118
		return this.store(pos, () -> value);
119
	}
120
121
	public CompletableFuture<Void> store(final ChunkPos pos, final Supplier<CompoundTag> supplier) {
122
		return this.<CompletableFuture<Void>>submitTask(() -> {
123
			CompoundTag data = supplier.get();
124
			IOWorker.PendingStore pendingStore = this.pendingWrites.computeIfAbsent(pos, p -> new IOWorker.PendingStore(data));
125
			pendingStore.data = data;
126
			return pendingStore.result;
127
		}).thenCompose(Function.identity());
128
	}
129
130
	public CompletableFuture<Optional<CompoundTag>> loadAsync(final ChunkPos pos) {
131
		return this.submitThrowingTask(() -> {
132
			IOWorker.PendingStore pendingStore = this.pendingWrites.get(pos);
133
			if (pendingStore != null) {
134
				return Optional.ofNullable(pendingStore.copyData());
135
			}
136
137
			try {
138
				CompoundTag data = this.storage.read(pos);
139
				return Optional.ofNullable(data);
140
			} catch (Exception e) {
141
				LOGGER.warn("Failed to read chunk {}", pos, e);
142
				throw e;
143
			}
144
		});
145
	}
146
147
	public CompletableFuture<Void> synchronize(final boolean flush) {
148
		CompletableFuture<Void> currentWrites = this.<CompletableFuture<Void>>submitTask(
149
				() -> CompletableFuture.allOf(this.pendingWrites.values().stream().map(store -> store.result).toArray(CompletableFuture[]::new))
150
			)
151
			.thenCompose(Function.identity());
152
		return flush ? currentWrites.thenCompose(ignore -> this.submitThrowingTask(() -> {
153
			try {
154
				this.storage.flush();
155
				return null;
156
			} catch (Exception e) {
157
				LOGGER.warn("Failed to synchronize chunks", e);
158
				throw e;
159
			}
160
		})) : currentWrites.thenCompose(ignore -> this.submitTask(() -> null));
161
	}
162
163
	@Override
164
	public CompletableFuture<Void> scanChunk(final ChunkPos pos, final StreamTagVisitor visitor) {
165
		return this.submitThrowingTask(() -> {
166
			try {
167
				IOWorker.PendingStore pendingStore = this.pendingWrites.get(pos);
168
				if (pendingStore != null) {
169
					if (pendingStore.data != null) {
170
						pendingStore.data.acceptAsRoot(visitor);
171
					}
172
				} else {
173
					this.storage.scanChunk(pos, visitor);
174
				}
175
176
				return null;
177
			} catch (Exception e) {
178
				LOGGER.warn("Failed to bulk scan chunk {}", pos, e);
179
				throw e;
180
			}
181
		});
182
	}
183
184
	private <T> CompletableFuture<T> submitThrowingTask(final IOWorker.ThrowingSupplier<T> task) {
185
		return this.consecutiveExecutor.scheduleWithResult(IOWorker.Priority.FOREGROUND.ordinal(), future -> {
186
			if (!this.shutdownRequested.get()) {
187
				try {
188
					future.complete(task.get());
189
				} catch (Exception e) {
190
					future.completeExceptionally(e);
191
				}
192
			}
193
194
			this.tellStorePending();
195
		});
196
	}
197
198
	private <T> CompletableFuture<T> submitTask(final Supplier<T> task) {
199
		return this.consecutiveExecutor.scheduleWithResult(IOWorker.Priority.FOREGROUND.ordinal(), future -> {
200
			if (!this.shutdownRequested.get()) {
201
				future.complete(task.get());
202
			}
203
204
			this.tellStorePending();
205
		});
206
	}
207
208
	private void storePendingChunk() {
209
		Entry<ChunkPos, IOWorker.PendingStore> entry = this.pendingWrites.pollFirstEntry();
210
		if (entry != null) {
211
			this.runStore(entry.getKey(), entry.getValue());
212
			this.tellStorePending();
213
		}
214
	}
215
216
	private void tellStorePending() {
217
		this.consecutiveExecutor.schedule(new StrictQueue.RunnableWithPriority(IOWorker.Priority.BACKGROUND.ordinal(), this::storePendingChunk));
218
	}
219
220
	private void runStore(final ChunkPos pos, final IOWorker.PendingStore write) {
221
		try {
222
			this.storage.write(pos, write.data);
223
			write.result.complete(null);
224
		} catch (Exception e) {
225
			LOGGER.error("Failed to store chunk {}", pos, e);
226
			write.result.completeExceptionally(e);
227
		}
228
	}
229
230
	@Override
231
	public void close() throws IOException {
232
		if (this.shutdownRequested.compareAndSet(false, true)) {
233
			this.waitForShutdown();
234
			this.consecutiveExecutor.close();
235
236
			try {
237
				this.storage.close();
238
			} catch (Exception e) {
239
				LOGGER.error("Failed to close storage", e);
240
			}
241
		}
242
	}
243
244
	private void waitForShutdown() {
245
		this.consecutiveExecutor.scheduleWithResult(IOWorker.Priority.SHUTDOWN.ordinal(), future -> future.complete(Unit.INSTANCE)).join();
246
	}
247
248
	public RegionStorageInfo storageInfo() {
249
		return this.storage.info();
250
	}
251
252
	private static class PendingStore {
253
		private @Nullable CompoundTag data;
254
		private final CompletableFuture<Void> result = new CompletableFuture<>();
255
256
		public PendingStore(final @Nullable CompoundTag data) {
257
			this.data = data;
258
		}
259
260
		private @Nullable CompoundTag copyData() {
261
			CompoundTag data = this.data;
262
			return data == null ? null : data.copy();
263
		}
264
	}
265
266
	private enum Priority {
267
		FOREGROUND,
268
		BACKGROUND,
269
		SHUTDOWN;
270
	}
271
272
	@FunctionalInterface
273
	private interface ThrowingSupplier<T> {
274
		@Nullable T get() throws Exception;
275
	}
276
}
277

Decompiled Minecraft 26.3 source of IOWorker (net/minecraft/world/level/chunk/storage/IOWorker.java) with Mojang official mappings, stored verbatim on the site.