-
Notifications
You must be signed in to change notification settings - Fork 630
Expand file tree
/
Copy pathTickerTask.java
More file actions
390 lines (333 loc) · 13.9 KB
/
TickerTask.java
File metadata and controls
390 lines (333 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package io.github.thebusybiscuit.slimefun4.implementation.tasks;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.scheduler.BukkitScheduler;
import io.github.bakedlibs.dough.blocks.BlockPosition;
import io.github.bakedlibs.dough.blocks.ChunkPosition;
import io.github.thebusybiscuit.slimefun4.api.ErrorReport;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem;
import io.github.thebusybiscuit.slimefun4.implementation.Slimefun;
import me.mrCookieSlime.CSCoreLibPlugin.Configuration.Config;
import me.mrCookieSlime.Slimefun.Objects.handlers.BlockTicker;
import me.mrCookieSlime.Slimefun.api.BlockStorage;
/**
* The {@link TickerTask} is responsible for ticking every {@link BlockTicker},
* synchronous or not.
*
* @author TheBusyBiscuit
*
* @see BlockTicker
*
*/
public class TickerTask implements Runnable {
/**
* This Map holds all currently actively ticking locations.
* The value of this map (Set entries) MUST be thread-safe and mutable.
*/
private final Map<ChunkPosition, Set<Location>> tickingLocations = new ConcurrentHashMap<>();
// These are "Queues" of blocks that need to be removed or moved
private final Map<Location, Location> movingQueue = new ConcurrentHashMap<>();
private final Map<Location, Boolean> deletionQueue = new ConcurrentHashMap<>();
/**
* This Map tracks how many bugs have occurred in a given Location .
* If too many bugs happen, we delete that Location.
*/
private final Map<BlockPosition, Integer> bugs = new ConcurrentHashMap<>();
private int tickRate;
private boolean halted = false;
private boolean running = false;
/**
* This method starts the {@link TickerTask} on an asynchronous schedule.
*
* @param plugin
* The instance of our {@link Slimefun}
*/
public void start(@Nonnull Slimefun plugin) {
this.tickRate = Slimefun.getCfg().getInt("URID.custom-ticker-delay");
BukkitScheduler scheduler = plugin.getServer().getScheduler();
scheduler.runTaskTimerAsynchronously(plugin, this, 100L, tickRate);
}
/**
* This method resets this {@link TickerTask} to run again.
*/
private void reset() {
running = false;
}
@Override
public void run() {
try {
// If this method is actually still running... DON'T
if (running) {
return;
}
running = true;
Slimefun.getProfiler().start();
Set<BlockTicker> tickers = new HashSet<>();
// Remove any deleted blocks
Iterator<Map.Entry<Location, Boolean>> removals = deletionQueue.entrySet().iterator();
while (removals.hasNext()) {
Map.Entry<Location, Boolean> entry = removals.next();
BlockStorage.deleteLocationInfoUnsafely(entry.getKey(), entry.getValue());
removals.remove();
}
// Fixes #2576 - Remove any deleted instances of BlockStorage
Slimefun.getRegistry().getWorlds().values().removeIf(BlockStorage::isMarkedForRemoval);
// Run our ticker code
if (!halted) {
for (Map.Entry<ChunkPosition, Set<Location>> entry : tickingLocations.entrySet()) {
tickChunk(entry.getKey(), tickers, entry.getValue());
}
}
// Move any moved block data
Iterator<Map.Entry<Location, Location>> moves = movingQueue.entrySet().iterator();
while (moves.hasNext()) {
Map.Entry<Location, Location> entry = moves.next();
BlockStorage.moveLocationInfoUnsafely(entry.getKey(), entry.getValue());
moves.remove();
}
// Start a new tick cycle for every BlockTicker
for (BlockTicker ticker : tickers) {
ticker.startNewTick();
}
reset();
Slimefun.getProfiler().stop();
} catch (Exception | LinkageError x) {
Slimefun.logger().log(Level.SEVERE, x, () -> "An Exception was caught while ticking the Block Tickers Task for Slimefun v" + Slimefun.getVersion());
reset();
}
}
@ParametersAreNonnullByDefault
private void tickChunk(ChunkPosition chunk, Set<BlockTicker> tickers, Set<Location> locations) {
try {
// Only continue if the Chunk is actually loaded
if (chunk.isLoaded()) {
for (Location l : new HashSet<>(locations)) {
tickLocation(tickers, l);
}
}
} catch (ArrayIndexOutOfBoundsException | NumberFormatException x) {
Slimefun.logger().log(Level.SEVERE, x, () -> "An Exception has occurred while trying to resolve Chunk: " + chunk);
}
}
private void tickLocation(@Nonnull Set<BlockTicker> tickers, @Nonnull Location l) {
Config data = BlockStorage.getLocationInfo(l);
SlimefunItem item = SlimefunItem.getById(data.getString("id"));
if (item != null && item.getBlockTicker() != null) {
try {
if (item.getBlockTicker().isSynchronized()) {
Slimefun.getProfiler().scheduleEntries(1);
item.getBlockTicker().update();
/**
* We are inserting a new timestamp because synchronized actions
* are always ran with a 50ms delay (1 game tick)
*/
Slimefun.runSync(() -> {
Block b = l.getBlock();
tickBlock(l, b, item, data, System.nanoTime());
});
} else {
long timestamp = Slimefun.getProfiler().newEntry();
item.getBlockTicker().update();
Block b = l.getBlock();
tickBlock(l, b, item, data, timestamp);
}
tickers.add(item.getBlockTicker());
} catch (Exception x) {
reportErrors(l, item, x);
}
}
}
@ParametersAreNonnullByDefault
private void tickBlock(Location l, Block b, SlimefunItem item, Config data, long timestamp) {
try {
item.getBlockTicker().tick(b, item, data);
} catch (Exception | LinkageError x) {
reportErrors(l, item, x);
} finally {
Slimefun.getProfiler().closeEntry(l, item, timestamp);
}
}
@ParametersAreNonnullByDefault
private void reportErrors(Location l, SlimefunItem item, Throwable x) {
BlockPosition position = new BlockPosition(l);
int errors = bugs.getOrDefault(position, 0) + 1;
if (errors == 1) {
// Generate a new Error-Report
new ErrorReport<>(x, l, item);
bugs.put(position, errors);
} else if (errors == 4) {
Slimefun.logger().log(Level.SEVERE, "X: {0} Y: {1} Z: {2} ({3})", new Object[] { l.getBlockX(), l.getBlockY(), l.getBlockZ(), item.getId() });
Slimefun.logger().log(Level.SEVERE, "has thrown 4 error messages in the last 4 Ticks, the Block has been terminated.");
Slimefun.logger().log(Level.SEVERE, "Check your /plugins/Slimefun/error-reports/ folder for details.");
Slimefun.logger().log(Level.SEVERE, " ");
bugs.remove(position);
BlockStorage.deleteLocationInfoUnsafely(l, true);
Bukkit.getScheduler().scheduleSyncDelayedTask(Slimefun.instance(), () -> l.getBlock().setType(Material.AIR));
} else {
bugs.put(position, errors);
}
}
public boolean isHalted() {
return halted;
}
public void halt() {
halted = true;
}
@ParametersAreNonnullByDefault
public void queueMove(Location from, Location to) {
Validate.notNull(from, "Source Location cannot be null!");
Validate.notNull(to, "Target Location cannot be null!");
movingQueue.put(from, to);
}
@ParametersAreNonnullByDefault
public void queueDelete(Location l, boolean destroy) {
Validate.notNull(l, "Location must not be null!");
deletionQueue.put(l, destroy);
}
@ParametersAreNonnullByDefault
public void queueDelete(Collection<Location> locations, boolean destroy) {
Validate.notNull(locations, "Locations must not be null");
Map<Location, Boolean> toDelete = new HashMap<>(locations.size(), 1.0F);
for (Location location : locations) {
Validate.notNull(location, "Locations must not contain null locations");
toDelete.put(location, destroy);
}
deletionQueue.putAll(toDelete);
}
@ParametersAreNonnullByDefault
public void queueDelete(Map<Location, Boolean> locations) {
Validate.notNull(locations, "Locations must not be null");
for (Map.Entry<Location, Boolean> entry : locations.entrySet()) {
Validate.notNull(entry.getKey(), "Location in locations cannot be null");
Validate.notNull(entry.getValue(), "Boolean toDestroy in locations cannot be null");
}
deletionQueue.putAll(locations);
}
/**
* This method checks if the given {@link Location} has been reserved
* by this {@link TickerTask}.
* A reserved {@link Location} does not currently hold any data but will
* be occupied upon the next tick.
* Checking this ensures that our {@link Location} does not get treated like a normal
* {@link Location} as it is theoretically "moving".
*
* @param l
* The {@link Location} to check
*
* @return Whether this {@link Location} has been reserved and will be filled upon the next tick
*/
public boolean isOccupiedSoon(@Nonnull Location l) {
Validate.notNull(l, "Null is not a valid Location!");
return movingQueue.containsValue(l);
}
/**
* This method checks if a given {@link Location} will be deleted on the next tick.
*
* @param l
* The {@link Location} to check
*
* @return Whether this {@link Location} will be deleted on the next tick
*/
public boolean isDeletedSoon(@Nonnull Location l) {
Validate.notNull(l, "Null is not a valid Location!");
return deletionQueue.containsKey(l);
}
/**
* This returns the delay between ticks
*
* @return The tick delay
*/
public int getTickRate() {
return tickRate;
}
/**
* This method returns a <strong>read-only</strong> {@link Map}
* representation of every {@link ChunkPosition} and its corresponding
* {@link Set} of ticking {@link Location Locations}.
*
* This does include any {@link Location} from an unloaded {@link Chunk} too!
*
* @return A {@link Map} representation of all ticking {@link Location Locations}
*/
@Nonnull
public Map<ChunkPosition, Set<Location>> getLocations() {
return Collections.unmodifiableMap(tickingLocations);
}
/**
* This method returns a <strong>read-only</strong> {@link Set}
* of all ticking {@link Location Locations} in a given {@link Chunk}.
* The {@link Chunk} does not have to be loaded.
* If no {@link Location} is present, the returned {@link Set} will be empty.
*
* @param chunk
* The {@link Chunk}
*
* @return A {@link Set} of all ticking {@link Location Locations}
*/
@Nonnull
public Set<Location> getLocations(@Nonnull Chunk chunk) {
Validate.notNull(chunk, "The Chunk cannot be null!");
Set<Location> locations = tickingLocations.getOrDefault(new ChunkPosition(chunk), Collections.emptySet());
return Collections.unmodifiableSet(locations);
}
/**
* This enables the ticker at the given {@link Location} and adds it to our "queue".
*
* @param l
* The {@link Location} to activate
*/
public void enableTicker(@Nonnull Location l) {
Validate.notNull(l, "Location cannot be null!");
ChunkPosition chunk = new ChunkPosition(l.getWorld(), l.getBlockX() >> 4, l.getBlockZ() >> 4);
/*
Note that all the values in #tickingLocations must be thread-safe.
Thus, the choice is between the CHM KeySet or a synchronized set.
The CHM KeySet was chosen since it at least permits multiple concurrent
reads without blocking.
*/
Set<Location> newValue = ConcurrentHashMap.newKeySet();
Set<Location> oldValue = tickingLocations.putIfAbsent(chunk, newValue);
/**
* This is faster than doing computeIfAbsent(...)
* on a ConcurrentHashMap because it won't block the Thread for too long
*/
if (oldValue != null) {
oldValue.add(l);
} else {
newValue.add(l);
}
}
/**
* This method disables the ticker at the given {@link Location} and removes it from our internal
* "queue".
*
* @param l
* The {@link Location} to remove
*/
public void disableTicker(@Nonnull Location l) {
Validate.notNull(l, "Location cannot be null!");
ChunkPosition chunk = new ChunkPosition(l.getWorld(), l.getBlockX() >> 4, l.getBlockZ() >> 4);
Set<Location> locations = tickingLocations.get(chunk);
if (locations != null) {
locations.remove(l);
if (locations.isEmpty()) {
tickingLocations.remove(chunk);
}
}
}
}