Single Thread Scheduled Executor For Processing

I was wondering what your opinions are of this:

;D

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class Game implements Runnable
{

	private ScheduledExecutorService service;
	private boolean running;

	public Game()
	{
		this.service = Executors.newSingleThreadScheduledExecutor();
		this.start();
	}

	public void start() {
		if (!running) {
			this.service.submit(this);
		}
	}

	public void stop() {
		this.running = false;
	}

	@Override
	public void run() {
		try {

			// Do stuff here.

			// Sleep
			Thread.sleep(50);

			// If we're still active, re-submit.
			if (this.running) {
				this.service.submit(this);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

what is wrong with a simple while loop^^
this is just overkill

Much as I like j.u.c and think everyone should use Executors … I have to agree, how’s this superior to a plain loop?

Well actually I never said this was superior to anything, I just asked for your opinions of it. ;D

I suppose you could say it’s properly tail recursive by way of using the executor as a trampoline, though with no proper way to take parameters or return output, that’s not a very interesting property, just a very expensive loop. If the executor were shared with other Runnables using it you’d have a poor man’s cooperative scheduler, emphasis on “poor”. Check out the green threads post for a heavy duty version of the same.

I’m pretty sure this is much slower than a simply while loop.

And It’s not tail recursive. If it would be tail recursive this would have been a cracy mess. The game would crash when reaching the maximal stack size, since afaik Java / JVM hasn’t got tail calls implemented yet.

It’s “tail recursive” in that run() reschedules itself then exits. Similar to how javascript typically runs infinite loops. It also doesn’t have any way to take input or produce a return value, though I suppose it would be simple to modify it for either.

Going back to my comment about sharing the executor, it’s not a bad thing to experiment. I’d encourage trying out that approach with several such runnables. Next, drive their execution from a blocking queue, and you have an actor system.