So, I have been doing a little Java Game programming for fun and I have seen two maybe three ways to do the game loop. I was just wondering if one is better then the other and why. So the first way and the way I currently do it is using javax.swing.Timer and a custom action listener. The second way I have seen is just a Thread using System.getTimeMillis() to get the timing, and the final one is the same as the second but using sleep() instead of System.getTimeMillis().

1) javax.swing.Timer - for lightweight games where the timer routine is very quick also if you want to use a swing gui and not have to worry about threading issues.2) Fixed sleep time, measure game time with System.nanoTime() - the best option for smooth animation, don't use currentTimeMillis() it is way less granular on some platforms.3) Fixed time step with a sleep for remainder - sleep generally has pretty low granularity worse for smooth animation but a fixed timestep can have quite a few advantages (stable/repeatable).

I wrote a tutorial on game loops on my website. Here's the source code if that's all your interested in. I need to do a little bit of fix up (I shouldn't have used doubles to represent the time in seconds), but it should work.

I had some weird problems using the game loop code from that book, though I admit that I did make a couple of small changes to it. The problems were only a significant issue on older computers, so it took me years to figure out what caused it. I deleted the portion of my game loop that was from Killer Game Programming in Java, and my code suddenly started working.

In all fairness, I did screw around with the Killer Game loop slightly. It's supposed to have an update phase that always uses a constant time period, but I made mine use a variable time period. I was losing time when the timer was too granular because it would still sleep or yield or whatever.

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org