1

I'm currently reading about game development, every time I see a game loop implemented it is always the same way.

A while(true) block, with a sleep inside for the FPS.

And I'm asking myself, why shouldn't I use a scheduledExcecutor, it seems like the obvious choice? I mean, I'm sure I'm wrong here, it's unlikely that I'm the first one to think of this, but WHY not ?

David Limkys
  • 4,907
  • 5
  • 26
  • 38

2 Answers2

0

First of all, look at some of the evolution of the traditional game loop. Your while(true) + sleep example is the simplest one.

Then people noticed that games were affected by the speed of the computer they were running on. Look up "variable time step game loop" on Google, for examples of how this is dealt with.

Now read over the docs on the ScheduledExecutorService. Neither scheduleAtFixedRate nor scheduleWithFixedDelay are quite what you'd want for a game.

Also, scrolling down in the docs, you'll notice "If any execution of the task encounters an exception, subsequent executions are suppressed." This can cause your game loop to abruptly terminate if you don't handle every possible exception.

There's nothing to stop you from extending the ScheduledExecutorService and modifying it to suit your needs, but I wouldn't recommend it as-is.

spudone
  • 1,267
  • 7
  • 10
  • Handling every possible exception is required for a while loop as well, no different for an executor. – Bill K Sep 26 '14 at 21:11
0

The main reason is probably simply that most of the code you are reading was coded before (or following patterns that were coded before) the concurrent package came out/was in heavy use.

A secondary might be trust. When you are coding something that critical to your app you want to be sure exactly how it behaves. The while(true) loop makes it very clear exactly what's going on... You'd have to spend some time dealing with the various executors before you became truly comfortable with one.

There should be a solution that solves your problem, I'm sure you can find something that fires regularly, and has an adjustment in case one iteration takes a little longer than expected.

You may even want to build your own executor. The pattern itself is fine, it's just finding a way to make it work for you.

Bill K
  • 62,186
  • 18
  • 105
  • 157