From acc8eb0a99cee28118274659739259ddc2cc062b Mon Sep 17 00:00:00 2001 From: matt <4009945+MattBDev@users.noreply.github.com> Date: Wed, 27 Mar 2019 12:17:05 -0400 Subject: [PATCH] Lambda's and References and Cleanups! Oh My! --- .../fawe/bukkit/v0/PaperChunkCallback.java | 4 +- .../src/main/java/com/boydti/fawe/Fawe.java | 45 ++--- .../boydti/fawe/example/MappedFaweQueue.java | 27 +-- .../fawe/example/NMSMappedFaweQueue.java | 13 +- .../boydti/fawe/jnbt/SchematicStreamer.java | 125 ++++-------- .../com/boydti/fawe/jnbt/anvil/MCAChunk.java | 168 +++++++--------- .../com/boydti/fawe/object/FawePlayer.java | 29 +-- .../java/com/boydti/fawe/util/SetQueue.java | 181 +++++++++--------- .../com/boydti/fawe/util/TaskManager.java | 14 +- .../java/com/boydti/fawe/util/WEManager.java | 50 ++--- .../boydti/fawe/util/task/TaskBuilder.java | 95 +++------ .../function/visitor/RegionVisitor.java | 2 +- 12 files changed, 291 insertions(+), 462 deletions(-) diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java index 369f9a71a..20592715a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java @@ -5,8 +5,8 @@ import org.bukkit.World; public abstract class PaperChunkCallback { public PaperChunkCallback(World world, int x, int z) { - world.getChunkAtAsync(x, z, chunk -> PaperChunkCallback.this.onLoad(chunk)); + world.getChunkAtAsync(x, z, PaperChunkCallback.this::onLoad); } public abstract void onLoad(Chunk chunk); -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java index 4829dd13c..ad22f754e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -152,10 +152,10 @@ public class Fawe { * The platform specific implementation */ private final IFawe IMP; - private Thread thread = Thread.currentThread(); + private Thread thread; private Fawe(final IFawe implementation) { - this.INSTANCE = this; + INSTANCE = this; this.IMP = implementation; this.thread = Thread.currentThread(); /* @@ -164,26 +164,18 @@ public class Fawe { this.setupConfigs(); TaskManager.IMP = this.IMP.getTaskManager(); - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false); - MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false); - } + TaskManager.IMP.async(() -> { + MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false); + MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false); }); if (Settings.IMP.METRICS) { try { this.stats = new BStats(); this.IMP.startMetrics(); - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - stats.start(); - } - }, 1); - } catch (Throwable ignore) { - ignore.printStackTrace(); + TaskManager.IMP.later(() -> stats.start(), 1); + } catch (Throwable throwable) { + throwable.printStackTrace(); } } /* @@ -216,7 +208,7 @@ public class Fawe { WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers()); WEManager.IMP.managers.add(new PlotSquaredFeature()); Fawe.debug("Plugin 'PlotSquared' found. Using it now."); - } catch (Throwable e) {} + } catch (Throwable ignored) {} }, 0); TaskManager.IMP.repeat(timer, 1); @@ -224,8 +216,8 @@ public class Fawe { if (!Settings.IMP.UPDATE.equalsIgnoreCase("false")) { // Delayed updating updater = new Updater(); - TaskManager.IMP.async(() -> update()); - TaskManager.IMP.repeatAsync(() -> update(), 36000); + TaskManager.IMP.async(this::update); + TaskManager.IMP.repeatAsync(this::update, 36000); } } @@ -452,16 +444,13 @@ public class Fawe { final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter ne = (NotificationEmitter) memBean; - ne.addNotificationListener(new NotificationListener() { - @Override - public void handleNotification(final Notification notification, final Object handback) { - final long heapSize = Runtime.getRuntime().totalMemory(); - final long heapMaxSize = Runtime.getRuntime().maxMemory(); - if (heapSize < heapMaxSize) { - return; - } - MemUtil.memoryLimitedTask(); + ne.addNotificationListener((notification, handback) -> { + final long heapSize = Runtime.getRuntime().totalMemory(); + final long heapMaxSize = Runtime.getRuntime().maxMemory(); + if (heapSize < heapMaxSize) { + return; } + MemUtil.memoryLimitedTask(); }, null, null); final List memPools = ManagementFactory.getMemoryPoolMXBeans(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java index 7645ef234..1c5c6fda8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java @@ -111,12 +111,7 @@ public abstract class MappedFaweQueue impl map.forEachChunk(new RunnableVal() { @Override public void run(final FaweChunk chunk) { - pool.submit(new Runnable() { - @Override - public void run() { - chunk.optimize(); - } - }); + pool.submit(chunk::optimize); } }); pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); @@ -300,8 +295,8 @@ public abstract class MappedFaweQueue impl @Override public boolean supports(Capability capability) { - switch (capability) { - case CHANGE_TASKS: return true; + if (capability == Capability.CHANGE_TASKS) { + return true; } return false; } @@ -416,12 +411,7 @@ public abstract class MappedFaweQueue impl public boolean queueChunkLoad(final int cx, final int cz) { CHUNK chunk = getCachedChunk(getWorld(), cx, cz); if (chunk == null) { - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - loadChunk(getWorld(), cx, cz, true); - } - }); + SetQueue.IMP.addTask(() -> loadChunk(getWorld(), cx, cz, true)); return true; } return false; @@ -430,12 +420,9 @@ public abstract class MappedFaweQueue impl public boolean queueChunkLoad(final int cx, final int cz, RunnableVal operation) { operation.value = getCachedChunk(getWorld(), cx, cz); if (operation.value == null) { - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - operation.value = loadChunk(getWorld(), cx, cz, true); - if (operation.value != null) TaskManager.IMP.async(operation); - } + SetQueue.IMP.addTask(() -> { + operation.value = loadChunk(getWorld(), cx, cz, true); + if (operation.value != null) TaskManager.IMP.async(operation); }); return true; } else { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java index 7c12c2878..33b475905 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java @@ -40,14 +40,11 @@ public abstract class NMSMappedFaweQueue ex public void runTasks() { super.runTasks(); if (!getRelighter().isEmpty()) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - if (getSettings().IMP.LIGHTING.REMOVE_FIRST) { - getRelighter().removeAndRelight(hasSky()); - } else { - getRelighter().fixLightingSafe(hasSky()); - } + TaskManager.IMP.async(() -> { + if (getSettings().IMP.LIGHTING.REMOVE_FIRST) { + getRelighter().removeAndRelight(hasSky()); + } else { + getRelighter().fixLightingSafe(hasSky()); } }); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java index 9ad05ceaa..2ecfc7101 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java @@ -133,39 +133,33 @@ public class SchematicStreamer extends NBTStreamer { addReader("Schematic.Biomes.#", biomeReader); // FAWE stores as a byte[] (4x smaller) // Tiles - addReader("Schematic.TileEntities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag value) { - if (fc == null) { - setupClipboard(0); - } - int x = value.getInt("x"); - int y = value.getInt("y"); - int z = value.getInt("z"); - fc.setTile(x, y, z, value); + addReader("Schematic.TileEntities.#", (BiConsumer) (index, value) -> { + if (fc == null) { + setupClipboard(0); } + int x = value.getInt("x"); + int y = value.getInt("y"); + int z = value.getInt("z"); + fc.setTile(x, y, z, value); }); // Entities - addReader("Schematic.Entities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag compound) { - if (fc == null) { - setupClipboard(0); - } - String id = compound.getString("id"); - if (id.isEmpty()) { - return; - } - ListTag positionTag = compound.getListTag("Pos"); - ListTag directionTag = compound.getListTag("Rotation"); - EntityType type = EntityTypes.parse(id); - if (type != null) { - compound.getValue().put("Id", new StringTag(type.getId())); - BaseEntity state = new BaseEntity(type, compound); - fc.createEntity(clipboard, positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2), (float) directionTag.asDouble(0), (float) directionTag.asDouble(1), state); - } else { - Fawe.debug("Invalid entity: " + id); - } + addReader("Schematic.Entities.#", (BiConsumer) (index, compound) -> { + if (fc == null) { + setupClipboard(0); + } + String id = compound.getString("id"); + if (id.isEmpty()) { + return; + } + ListTag positionTag = compound.getListTag("Pos"); + ListTag directionTag = compound.getListTag("Rotation"); + EntityType type = EntityTypes.parse(id); + if (type != null) { + compound.getValue().put("Id", new StringTag(type.getId())); + BaseEntity state = new BaseEntity(type, compound); + fc.createEntity(clipboard, positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2), (float) directionTag.asDouble(0), (float) directionTag.asDouble(1), state); + } else { + Fawe.debug("Invalid entity: " + id); } }); } @@ -345,60 +339,23 @@ public class SchematicStreamer extends NBTStreamer { } public void addDimensionReaders() { - addReader("Schematic.Height", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - height = (value); - } - }); - addReader("Schematic.Width", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - width = (value); - } - }); - addReader("Schematic.Length", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - length = (value); - } - }); - addReader("Schematic.WEOriginX", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originX = (value); - } - }); - addReader("Schematic.WEOriginY", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originY = (value); - } - }); - addReader("Schematic.WEOriginZ", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originZ = (value); - } - }); - addReader("Schematic.WEOffsetX", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetX = (value); - } - }); - addReader("Schematic.WEOffsetY", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetY = (value); - } - }); - addReader("Schematic.WEOffsetZ", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetZ = (value); - } - }); + addReader("Schematic.Height", + (BiConsumer) (index, value) -> height = (value)); + addReader("Schematic.Width", (BiConsumer) (index, value) -> width = (value)); + addReader("Schematic.Length", + (BiConsumer) (index, value) -> length = (value)); + addReader("Schematic.WEOriginX", + (BiConsumer) (index, value) -> originX = (value)); + addReader("Schematic.WEOriginY", + (BiConsumer) (index, value) -> originY = (value)); + addReader("Schematic.WEOriginZ", + (BiConsumer) (index, value) -> originZ = (value)); + addReader("Schematic.WEOffsetX", + (BiConsumer) (index, value) -> offsetX = (value)); + addReader("Schematic.WEOffsetY", + (BiConsumer) (index, value) -> offsetY = (value)); + addReader("Schematic.WEOffsetZ", + (BiConsumer) (index, value) -> offsetZ = (value)); } private int height; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java index 801f5707e..b90c63794 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java @@ -91,50 +91,47 @@ public class MCAChunk extends FaweChunk { public void write(NBTOutputStream nbtOut) throws IOException { nbtOut.writeNamedTagName("", NBTConstants.TYPE_COMPOUND); - nbtOut.writeLazyCompoundTag("Level", new NBTOutputStream.LazyWrite() { - @Override - public void write(NBTOutputStream out) throws IOException { - out.writeNamedTag("V", (byte) 1); - out.writeNamedTag("xPos", getX()); - out.writeNamedTag("zPos", getZ()); - out.writeNamedTag("LightPopulated", (byte) 0); - out.writeNamedTag("TerrainPopulated", (byte) 1); - if (entities.isEmpty()) { - out.writeNamedEmptyList("Entities"); - } else { - out.writeNamedTag("Entities", new ListTag(CompoundTag.class, new ArrayList<>(entities.values()))); - } - if (tiles.isEmpty()) { - out.writeNamedEmptyList("TileEntities"); - } else { - out.writeNamedTag("TileEntities", new ListTag(CompoundTag.class, - new ArrayList<>(tiles.values()))); - } - out.writeNamedTag("InhabitedTime", inhabitedTime); - out.writeNamedTag("LastUpdate", lastUpdate); - if (biomes != null) { - out.writeNamedTag("Biomes", biomes); - } - out.writeNamedTag("HeightMap", heightMap); - out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST); - nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND); - int len = 0; - for (int layer = 0; layer < ids.length; layer++) { - if (ids[layer] != null) len++; - } - nbtOut.getOutputStream().writeInt(len); - for (int layer = 0; layer < ids.length; layer++) { - byte[] idLayer = ids[layer]; - if (idLayer == null) { - continue; - } - out.writeNamedTag("Y", (byte) layer); - out.writeNamedTag("BlockLight", blockLight[layer]); - out.writeNamedTag("SkyLight", skyLight[layer]); - out.writeNamedTag("Blocks", idLayer); - out.writeNamedTag("Data", data[layer]); - out.writeEndTag(); + nbtOut.writeLazyCompoundTag("Level", out -> { + out.writeNamedTag("V", (byte) 1); + out.writeNamedTag("xPos", getX()); + out.writeNamedTag("zPos", getZ()); + out.writeNamedTag("LightPopulated", (byte) 0); + out.writeNamedTag("TerrainPopulated", (byte) 1); + if (entities.isEmpty()) { + out.writeNamedEmptyList("Entities"); + } else { + out.writeNamedTag("Entities", new ListTag(CompoundTag.class, new ArrayList<>(entities.values()))); + } + if (tiles.isEmpty()) { + out.writeNamedEmptyList("TileEntities"); + } else { + out.writeNamedTag("TileEntities", new ListTag(CompoundTag.class, + new ArrayList<>(tiles.values()))); + } + out.writeNamedTag("InhabitedTime", inhabitedTime); + out.writeNamedTag("LastUpdate", lastUpdate); + if (biomes != null) { + out.writeNamedTag("Biomes", biomes); + } + out.writeNamedTag("HeightMap", heightMap); + out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST); + nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND); + int len = 0; + for (int layer = 0; layer < ids.length; layer++) { + if (ids[layer] != null) len++; + } + nbtOut.getOutputStream().writeInt(len); + for (int layer = 0; layer < ids.length; layer++) { + byte[] idLayer = ids[layer]; + if (idLayer == null) { + continue; } + out.writeNamedTag("Y", (byte) layer); + out.writeNamedTag("BlockLight", blockLight[layer]); + out.writeNamedTag("SkyLight", skyLight[layer]); + out.writeNamedTag("Blocks", idLayer); + out.writeNamedTag("Data", data[layer]); + out.writeEndTag(); } }); nbtOut.writeEndTag(); @@ -464,74 +461,43 @@ public class MCAChunk extends FaweChunk { skyLight = new byte[16][]; blockLight = new byte[16][]; NBTStreamer streamer = new NBTStreamer(nis); - streamer.addReader(".Level.InhabitedTime", new BiConsumer() { - @Override - public void accept(Integer index, Long value) { - inhabitedTime = value; - } + streamer.addReader(".Level.InhabitedTime", + (BiConsumer) (index, value) -> inhabitedTime = value); + streamer.addReader(".Level.LastUpdate", + (BiConsumer) (index, value) -> lastUpdate = value); + streamer.addReader(".Level.Sections.#", (BiConsumer) (index, tag) -> { + int layer = tag.getByte("Y"); + ids[layer] = tag.getByteArray("Blocks"); + data[layer] = tag.getByteArray("Data"); + skyLight[layer] = tag.getByteArray("SkyLight"); + blockLight[layer] = tag.getByteArray("BlockLight"); }); - streamer.addReader(".Level.LastUpdate", new BiConsumer() { - @Override - public void accept(Integer index, Long value) { - lastUpdate = value; - } - }); - streamer.addReader(".Level.Sections.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag tag) { - int layer = tag.getByte("Y"); - ids[layer] = tag.getByteArray("Blocks"); - data[layer] = tag.getByteArray("Data"); - skyLight[layer] = tag.getByteArray("SkyLight"); - blockLight[layer] = tag.getByteArray("BlockLight"); - } - }); - streamer.addReader(".Level.TileEntities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag tile) { - int x = tile.getInt("x") & 15; + streamer.addReader(".Level.TileEntities.#", + (BiConsumer) (index, tile) -> { + int x1 = tile.getInt("x") & 15; int y = tile.getInt("y"); - int z = tile.getInt("z") & 15; - short pair = MathMan.tripleBlockCoord(x, y, z); + int z1 = tile.getInt("z") & 15; + short pair = MathMan.tripleBlockCoord(x1, y, z1); tiles.put(pair, tile); - } - }); - streamer.addReader(".Level.Entities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag entityTag) { + }); + streamer.addReader(".Level.Entities.#", + (BiConsumer) (index, entityTag) -> { if (entities == null) { entities = new HashMap<>(); } long least = entityTag.getLong("UUIDLeast"); long most = entityTag.getLong("UUIDMost"); entities.put(new UUID(most, least), entityTag); - } - }); - streamer.addReader(".Level.Biomes", new BiConsumer() { - @Override - public void accept(Integer index, byte[] value) { - biomes = value; - } - }); - streamer.addReader(".Level.HeightMap", new BiConsumer() { - @Override - public void accept(Integer index, int[] value) { - heightMap = value; - } - }); + }); + streamer.addReader(".Level.Biomes", + (BiConsumer) (index, value) -> biomes = value); + streamer.addReader(".Level.HeightMap", + (BiConsumer) (index, value) -> heightMap = value); if (readPos) { - streamer.addReader(".Level.xPos", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - MCAChunk.this.setLoc(getParent(), value, getZ()); - } - }); - streamer.addReader(".Level.zPos", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - MCAChunk.this.setLoc(getParent(), getX(), value); - } - }); + streamer.addReader(".Level.xPos", + (BiConsumer) (index, value) -> MCAChunk.this.setLoc(getParent(), value, getZ())); + streamer.addReader(".Level.zPos", + (BiConsumer) (index, value) -> MCAChunk.this.setLoc(getParent(), getX(), value)); } streamer.readFully(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java index 068b5564e..7c621d460 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java @@ -9,7 +9,6 @@ import com.boydti.fawe.object.brush.visualization.VirtualWorld; import com.boydti.fawe.object.clipboard.DiskOptimizedClipboard; import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.task.SimpleAsyncNotifyQueue; -import com.boydti.fawe.object.task.ThrowableSupplier; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.util.*; import com.boydti.fawe.wrappers.FakePlayer; @@ -17,8 +16,7 @@ import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper; import com.boydti.fawe.wrappers.PlayerWrapper; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.command.tool.BrushTool; -import com.sk89q.worldedit.command.tool.Tool; + import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.*; @@ -41,7 +39,6 @@ import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; public abstract class FawePlayer extends Metadatable { @@ -164,18 +161,10 @@ public abstract class FawePlayer extends Metadatable { private void setConfirmTask(@Nullable Runnable task, CommandContext context, String command) { if (task != null) { - Runnable newTask = new Runnable() { - @Override - public void run() { - CommandManager.getInstance().handleCommandTask(new ThrowableSupplier() { - @Override - public Object get() throws Throwable { - task.run(); - return null; - } - }, context.getLocals()); - } - }; + Runnable newTask = () -> CommandManager.getInstance().handleCommandTask(() -> { + task.run(); + return null; + }, context.getLocals()); setMeta("cmdConfirm", newTask); } else { setMeta("cmdConfirm", new CommandEvent(getPlayer(), command)); @@ -365,15 +354,15 @@ public abstract class FawePlayer extends Metadatable { } } catch (EmptyClipboardException e) { } - if (player != null && session != null) { + if (player != null) { Clipboard clip = doc.toClipboard(); ClipboardHolder holder = new ClipboardHolder(clip); getSession().setClipboard(holder); } } - } catch (Exception ignore) { + } catch (Exception event) { Fawe.debug("====== INVALID CLIPBOARD ======"); - MainUtil.handleError(ignore, false); + MainUtil.handleError(event, false); Fawe.debug("===============---============="); Fawe.debug("This shouldn't result in any failure"); Fawe.debug("File: " + file.getName() + " (len:" + file.length() + ")"); @@ -734,4 +723,4 @@ public abstract class FawePlayer extends Metadatable { } return map; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java index 191bed5b0..28a174870 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java @@ -73,120 +73,117 @@ public class SetQueue { public SetQueue() { tasks = new ConcurrentLinkedDeque<>(); - activeQueues = new ConcurrentLinkedDeque(); + activeQueues = new ConcurrentLinkedDeque<>(); inactiveQueues = new ConcurrentLinkedDeque<>(); if (TaskManager.IMP == null) return; - TaskManager.IMP.repeat(new Runnable() { - @Override - public void run() { - try { - long now = System.currentTimeMillis(); - boolean empty = (inactiveQueues.isEmpty() && activeQueues.isEmpty()); - boolean emptyTasks = tasks.isEmpty(); - if (emptyTasks && empty) { - last = now; - runEmptyTasks(); - return; - } + TaskManager.IMP.repeat(() -> { + try { + long now = System.currentTimeMillis(); + boolean empty = (inactiveQueues.isEmpty() && activeQueues.isEmpty()); + boolean emptyTasks = tasks.isEmpty(); + if (emptyTasks && empty) { + last = now; + runEmptyTasks(); + return; + } - targetTPS = 18 - Math.max(Settings.IMP.QUEUE.EXTRA_TIME_MS * 0.05, 0); + targetTPS = 18 - Math.max(Settings.IMP.QUEUE.EXTRA_TIME_MS * 0.05, 0); - long diff = (50 + SetQueue.this.last) - (SetQueue.this.last = now); - long absDiff = Math.abs(diff); - if (diff == 0) { - allocate = Math.min(50, allocate + 1); - } else if (diff < 0) { - allocate = Math.max(5, allocate + diff); - } else if (!Fawe.get().getTimer().isAbove(targetTPS)) { - allocate = Math.max(5, allocate - 1); - } + long diff = (50 + SetQueue.this.last) - (SetQueue.this.last = now); + long absDiff = Math.abs(diff); + if (diff == 0) { + allocate = Math.min(50, allocate + 1); + } else if (diff < 0) { + allocate = Math.max(5, allocate + diff); + } else if (!Fawe.get().getTimer().isAbove(targetTPS)) { + allocate = Math.max(5, allocate - 1); + } - long currentAllocate = allocate - absDiff; + long currentAllocate = allocate - absDiff; - if (!emptyTasks) { - long taskAllocate = activeQueues.isEmpty() ? currentAllocate : 1 + (currentAllocate >> 1); - long used = 0; - boolean wait = false; - do { - Runnable task = tasks.poll(); - if (task == null) { - if (wait) { - synchronized (tasks) { - tasks.wait(1); - } - task = tasks.poll(); - wait = false; - } else { - break; + if (!emptyTasks) { + long taskAllocate = activeQueues.isEmpty() ? currentAllocate : 1 + (currentAllocate >> 1); + long used = 0; + boolean wait = false; + do { + Runnable task = tasks.poll(); + if (task == null) { + if (wait) { + synchronized (tasks) { + tasks.wait(1); } - } - if (task != null) { - task.run(); - wait = true; - } - } while ((used = System.currentTimeMillis() - now) < taskAllocate); - currentAllocate -= used; - } - - if (empty) { - runEmptyTasks(); - return; - } - - if (!MemUtil.isMemoryFree()) { - final int mem = MemUtil.calculateMemory(); - if (mem != Integer.MAX_VALUE) { - allocate = Math.max(5, allocate - 1); - if ((mem <= 1) && Settings.IMP.PREVENT_CRASHES) { - for (FaweQueue queue : getAllQueues()) { - queue.saveMemory(); - } - return; - } - if (SetQueue.this.forceChunkSet()) { - System.gc(); + task = tasks.poll(); + wait = false; } else { - SetQueue.this.runEmptyTasks(); + break; + } + } + if (task != null) { + task.run(); + wait = true; + } + } while ((used = System.currentTimeMillis() - now) < taskAllocate); + currentAllocate -= used; + } + + if (empty) { + runEmptyTasks(); + return; + } + + if (!MemUtil.isMemoryFree()) { + final int mem = MemUtil.calculateMemory(); + if (mem != Integer.MAX_VALUE) { + allocate = Math.max(5, allocate - 1); + if ((mem <= 1) && Settings.IMP.PREVENT_CRASHES) { + for (FaweQueue queue : getAllQueues()) { + queue.saveMemory(); } return; } - } - - FaweQueue queue = getNextQueue(); - if (queue == null) { + if (SetQueue.this.forceChunkSet()) { + System.gc(); + } else { + SetQueue.this.runEmptyTasks(); + } return; } + } - long time = (long) Settings.IMP.QUEUE.EXTRA_TIME_MS + currentAllocate - System.currentTimeMillis() + now; - // Disable the async catcher as it can't discern async vs parallel - boolean parallel = Settings.IMP.QUEUE.PARALLEL_THREADS > 1; - queue.startSet(parallel); - try { - if (!queue.next(Settings.IMP.QUEUE.PARALLEL_THREADS, time) && queue.getStage() == QueueStage.ACTIVE) { - queue.setStage(QueueStage.NONE); - queue.runTasks(); - } - } catch (Throwable e) { - pool.awaitQuiescence(Settings.IMP.QUEUE.DISCARD_AFTER_MS, TimeUnit.MILLISECONDS); - completer = new ExecutorCompletionService(pool); - e.printStackTrace(); + FaweQueue queue = getNextQueue(); + if (queue == null) { + return; + } + + long time = (long) Settings.IMP.QUEUE.EXTRA_TIME_MS + currentAllocate - System.currentTimeMillis() + now; + // Disable the async catcher as it can't discern async vs parallel + boolean parallel = Settings.IMP.QUEUE.PARALLEL_THREADS > 1; + queue.startSet(parallel); + try { + if (!queue.next(Settings.IMP.QUEUE.PARALLEL_THREADS, time) && queue.getStage() == QueueStage.ACTIVE) { + queue.setStage(QueueStage.NONE); + queue.runTasks(); } - if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) { + } catch (Throwable e) { + pool.awaitQuiescence(Settings.IMP.QUEUE.DISCARD_AFTER_MS, TimeUnit.MILLISECONDS); + completer = new ExecutorCompletionService(pool); + e.printStackTrace(); + } + if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) { // if (Fawe.get().isJava8()) - { - pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); - } + { + pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); + } // else { // pool.shutdown(); // pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); // pool = new ForkJoinPool(); // completer = new ExecutorCompletionService(pool); // } - } - queue.endSet(parallel); - } catch (Throwable e) { - e.printStackTrace(); } + queue.endSet(parallel); + } catch (Throwable e) { + e.printStackTrace(); } }, 1); } @@ -264,7 +261,7 @@ public class SetQueue { public void flush(FaweQueue queue) { int parallelThreads; - if (Fawe.get().isMainThread()) { + if (Fawe.isMainThread()) { parallelThreads = Settings.IMP.QUEUE.PARALLEL_THREADS; Settings.IMP.QUEUE.PARALLEL_THREADS = 1; } else { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java b/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java index 934926d95..8b8fb9ab6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java @@ -124,14 +124,10 @@ public abstract class TaskManager { } for (i = 0; i < threads.length; i++) { final Runnable[] toRun = split[i]; - Thread thread = threads[i] = new Thread(new Runnable() { - @Override - public void run() { - for (int j = 0; j < toRun.length; j++) { - Runnable run = toRun[j]; - if (run != null) { - run.run(); - } + Thread thread = threads[i] = new Thread(() -> { + for (Runnable run : toRun) { + if (run != null) { + run.run(); } } }); @@ -420,7 +416,7 @@ public abstract class TaskManager { } catch (InterruptedException e) { MainUtil.handleError(e); } - if (run.value != null && run.value instanceof RuntimeException) { + if (run.value instanceof RuntimeException) { throw (RuntimeException) run.value; } return (T) run.value; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java b/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java index ef0f5fc33..b7ecabf2b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java @@ -124,7 +124,7 @@ public class WEManager { } } } - if (!removed) return regions.toArray(new Region[regions.size()]); + if (!removed) return regions.toArray(new Region[0]); masks.clear(); } } @@ -146,7 +146,7 @@ public class WEManager { } if (!tmpMasks.isEmpty()) { masks = tmpMasks; - regions = masks.stream().map(mask -> mask.getRegion()).collect(Collectors.toSet()); + regions = masks.stream().map(FaweMask::getRegion).collect(Collectors.toSet()); } else { regions.addAll(backupRegions); } @@ -155,7 +155,7 @@ public class WEManager { } else { player.deleteMeta("lastMask"); } - return regions.toArray(new Region[regions.size()]); + return regions.toArray(new Region[0]); } @@ -179,36 +179,22 @@ public class WEManager { public boolean delay(final FawePlayer player, final String command) { final long start = System.currentTimeMillis(); - return this.delay(player, new Runnable() { - @Override - public void run() { - try { - if ((System.currentTimeMillis() - start) > 1000) { - BBC.WORLDEDIT_RUN.send(FawePlayer.wrap(player)); - } - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - final long start = System.currentTimeMillis(); - player.executeCommand(command.substring(1)); - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - SetQueue.IMP.addEmptyTask(new Runnable() { - @Override - public void run() { - if ((System.currentTimeMillis() - start) > 1000) { - BBC.WORLDEDIT_COMPLETE.send(FawePlayer.wrap(player)); - } - } - }); - } - }, 2); - } - }); - } catch (final Exception e) { - MainUtil.handleError(e); + return this.delay(player, () -> { + try { + if ((System.currentTimeMillis() - start) > 1000) { + BBC.WORLDEDIT_RUN.send(FawePlayer.wrap(player)); } + TaskManager.IMP.task(() -> { + final long start1 = System.currentTimeMillis(); + player.executeCommand(command.substring(1)); + TaskManager.IMP.later(() -> SetQueue.IMP.addEmptyTask(() -> { + if ((System.currentTimeMillis() - start1) > 1000) { + BBC.WORLDEDIT_COMPLETE.send(FawePlayer.wrap(player)); + } + }), 2); + }); + } catch (final Exception e) { + MainUtil.handleError(e); } }, false, false); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java index adc56e908..74b7959cf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java @@ -167,45 +167,33 @@ public class TaskBuilder extends Metadatable { } public TaskBuilder abortIfTrue(final Runnable run) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Boolean previous) { - if (previous == Boolean.TRUE) run.run(); - return previous == Boolean.TRUE; - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (previous == Boolean.TRUE) run.run(); + return previous == Boolean.TRUE; }, TaskType.ABORT)); return this; } public TaskBuilder abortIfNull(final Runnable run) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (previous == null) run.run(); - return previous == null; - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (previous == null) run.run(); + return previous == null; }, TaskType.ABORT)); return this; } public TaskBuilder abortIfEqual(final Runnable run, final Object other) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (Objects.equals(previous, other)) run.run(); - return Objects.equals(previous, other); - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (Objects.equals(previous, other)) run.run(); + return Objects.equals(previous, other); }, TaskType.ABORT)); return this; } public TaskBuilder abortIfNotEqual(final Runnable run, final Object other) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (!Objects.equals(previous, other)) run.run(); - return !Objects.equals(previous, other); - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (!Objects.equals(previous, other)) run.run(); + return !Objects.equals(previous, other); }, TaskType.ABORT)); return this; } @@ -215,12 +203,7 @@ public class TaskBuilder extends Metadatable { * - As opposed to trying to using the current thread */ public void buildAsync() { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - build(); - } - }); + TaskManager.IMP.async(this::build); } /** @@ -240,20 +223,10 @@ public class TaskBuilder extends Metadatable { case SYNC: case ABORT: case SYNC_PARALLEL: - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - build(); - } - }, task.getDelay(result)); + TaskManager.IMP.later(this::build, task.getDelay(result)); return; default: - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - build(); - } - }, task.getDelay(result)); + TaskManager.IMP.laterAsync(this::build, task.getDelay(result)); return; } } @@ -274,12 +247,7 @@ public class TaskBuilder extends Metadatable { case ASYNC: case ASYNC_PARALLEL: if (Fawe.isMainThread()) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - build(); - } - }); + TaskManager.IMP.async(this::build); return; } break; @@ -484,24 +452,21 @@ public class TaskBuilder extends Metadatable { public Object execSplit(final Object previous) { this.value = previous; - final Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - synchronized (asyncWaitLock) { - asyncWaitLock.notifyAll(); - asyncWaitLock.wait(Long.MAX_VALUE); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - exec(previous); - finished = true; - waitingAsync = true; - waitingSync = false; - synchronized (syncWaitLock) { - syncWaitLock.notifyAll(); + final Thread thread = new Thread(() -> { + try { + synchronized (asyncWaitLock) { + asyncWaitLock.notifyAll(); + asyncWaitLock.wait(Long.MAX_VALUE); } + } catch (InterruptedException e) { + e.printStackTrace(); + } + exec(previous); + finished = true; + waitingAsync = true; + waitingSync = false; + synchronized (syncWaitLock) { + syncWaitLock.notifyAll(); } }); try { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java index fb3533896..9e62b58b5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java @@ -166,7 +166,7 @@ public class RegionVisitor implements Operation { } catch (Throwable ignore) { } try { - for (; ; ) { + while (true) { apply(trailIter.next()); apply(trailIter.next()); }