Skip to content

Commit

Permalink
add throttle to calculate chunks (#102)
Browse files Browse the repository at this point in the history
* add throttle to calculate chunks

* dont think the synchronized is needed
  • Loading branch information
PhanaticD authored and tastybento committed Nov 23, 2019
1 parent 7803e71 commit 0eb3881
Showing 1 changed file with 26 additions and 16 deletions.
42 changes: 26 additions & 16 deletions src/main/java/world/bentobox/level/calculators/CalcIslandLevel.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
package world.bentobox.level.calculators;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

Expand Down Expand Up @@ -49,10 +42,11 @@ public class CalcIslandLevel {
private final List<World> worlds;
private final World world;

private int count;
private AtomicInteger count;

private int total;

private Queue<Chunk> q;
private int queueid;

/**
* Calculate the island's level
Expand All @@ -69,7 +63,7 @@ public CalcIslandLevel(final Level addon, final Island island, final Runnable on
this.onExit = onExit;
this.worlds = new ArrayList<>();
this.worlds.add(world);

q = new LinkedList<>();

// Results go here
result = new Results();
Expand All @@ -79,7 +73,7 @@ public CalcIslandLevel(final Level addon, final Island island, final Runnable on

// Get chunks to scan
chunksToScan = getChunksToScan(island);
count = 0;
count = new AtomicInteger();
// Total number of chunks to scan
total = chunksToScan.size();
// Add nether world scanning
Expand All @@ -98,17 +92,33 @@ public CalcIslandLevel(final Level addon, final Island island, final Runnable on
total += chunksToScan.size();
}
}
queueid = Bukkit.getScheduler().scheduleSyncRepeatingTask(addon.getPlugin(), new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
if (q.size() == 0) {
return;
}
Chunk c = q.remove();
getChunk(c);
}
}
}, 1L, 1L);
chunksToScan.forEach(c -> worlds.forEach(w -> Util.getChunkAtAsync(w, c.x, c.z).thenAccept(this::addChunkQueue)));

chunksToScan.forEach(c -> worlds.forEach(w -> Util.getChunkAtAsync(w, c.x, c.z).thenAccept(this::getChunk)));
}

private void addChunkQueue(Chunk ch) {
q.add(ch);
}

private void getChunk(Chunk ch) {
private void getChunk(Chunk ch) {
ChunkSnapshot snapShot = ch.getChunkSnapshot();

Bukkit.getScheduler().runTaskAsynchronously(addon.getPlugin(), () -> {
this.scanChunk(snapShot);
count++;
if (count == total) {
count.getAndIncrement();
if (count.get() == total) {
Bukkit.getScheduler().cancelTask(queueid);
this.tidyUp();
}
});
Expand Down

0 comments on commit 0eb3881

Please sign in to comment.