package net.morematerials.wgen.async;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

import net.morematerials.wgen.Decorator;
import net.morematerials.wgen.Timer;
import org.bukkit.Chunk;
import org.bukkit.World;

public class DecoratorThrottler extends Thread {
	private final Queue<DecorableEntry> queue;
	private final Timer timer;
	private final World world;
	private volatile boolean running = false;

	public DecoratorThrottler(int tps, World world) {
		timer = new Timer(tps);
		this.world = world;
		queue = new LinkedBlockingQueue<>();
	}

	@Override
	public void run() {
		running = true;
		long lastTime = System.nanoTime() - (long) (1f / timer.getTps() * 1000000000), currentTime;
		while (running) {
			currentTime = System.nanoTime() - lastTime;
			final DecorableEntry entry = queue.poll();
			entry.getDecorator().decorate(world, entry.getChunk(), entry.getRandom());
			System.out.println("Decorated: [" + entry.getChunk() + "]");
			lastTime = currentTime;
			timer.sync();
		}
	}

	public void terminate() {
		running = false;
	}

	public void offer(Decorator decorator, Chunk chunk, Random random) {
		if (chunk.getWorld() != world) {
			throw new RuntimeException("Attempt to throttle decoration of a chunk within another world!");
		}
		queue.offer(new DecorableEntry(decorator, chunk, random));
	}
}

@@ -1,8 +1,1230 @@
+/*%0A * This file is part of MoreMaterials, licensed under the MIT License (MIT).%0A *%0A * Copyright (c) 2013 AlmuraDev %3Chttp://www.almuradev.com/%3E%0A *%0A * Permission is hereby granted, free of charge, to any person obtaining a copy%0A * of this software and associated documentation files (the %22Software%22), to deal%0A * in the Software without restriction, including without limitation the rights%0A * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A * copies of the Software, and to permit persons to whom the Software is%0A * furnished to do so, subject to the following conditions:%0A *%0A * The above copyright notice and this permission notice shall be included in%0A * all copies or substantial portions of the Software.%0A *%0A * THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A * THE SOFTWARE.%0A */%0A
 package 
@@ -2074,16 +2074,41 @@
 poll();%0A
+%09%09%09if (entry != null) %7B%0A%09
 %09%09%09entry
@@ -2180,16 +2180,17 @@
 ());%0A%09%09%09
+%09
 System.o
@@ -2242,16 +2242,21 @@
 + %22%5D%22);%0A
+%09%09%09%7D%0A
 %09%09%09lastT

Call decorate on valid poll entries. Sync anyhow.