Thread.yield()

I was just looking at my 4k game and I noticed Thread.yield() - copied from the applet templates thread (http://www.java-gaming.org/topics/applet-templates/21626/view.html), specifically groboclown’s reply number 5 (it’s from 2009)

I was wondering what it did so I read this (http://www.javamex.com/tutorials/threads/yield.shtml) and it says not to use thread.yield, instead to use thread.sleep, however I seem to hear people recommending against thread.sleep(). Exactly what is so bad about yield, and what should I use instead?

Thread.yield() is basically just a suggestion, and the platform is free to ignore that suggestion. I remember reading some code for Hotspot on Solaris where it does exactly that if you yield too many times in a short interval. Even if it always yields, it still forces immediate re-scheduling, which can interfere with the CPU actually sleeping when idle.

If you really have nothing to do, sleeping even a millisecond in a tight loop can save you a lot of CPU usage over a bare yield. Mobile users will thank you. Now if you have precise frame deadlines and your timer is out of whack (that is, you’re on Windows), then Thread.yield() in a spin loop might be exactly what you need.

I tried several methods, and yield makes no sense in a game loop. It tells the scheduler that works it’s doing is not that important and that it can go ahead and move to the next time slice. What I do in my tight render loop is lock it at a max of 59.9something FPS:

    public void run() {
        while (_running) {
            final long newTime = System.currentTimeMillis();

            if ((newTime - _lastProcessed) < GAME_MINFRAMETIME) {
                try {
                    Thread.sleep((long) (GAME_MINFRAMETIME - (newTime - _lastProcessed)));
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }
            _lastProcessed = newTime;
            try {
                renderGraphics();
                handleMessages();
                if (_currentScreen != null) {
                    _currentScreen.update();
                }
            } catch (final Exception e) {
                e.printStackTrace();
                stop();
            }
        }
    }

This slows the thread down if it’s running 60+ fps. When I look in the profiler it shows the thread obediently sleeping when needed, allowing other threaded loops to execute before returning back to the render logic.

Thread.Sleep tells the system to not execute the thread for x amount of time – this means it literally gives absolutely 0 CPU time to the thread until the time has passed (this is an operating system related thing). I highly prefer thread.sleep when used properly.

Thats a sound statement. You clearly have not tested all OS/CPU combinations out there. There are a lot of threads in this forum regarding game loops and there are enough posts stating, that a tight yield loop is the only method getting a stable frame-rate on their OS/CPU combination.

Still it remains true, that a Thread.sleep() should be prefered and there is also a deamon-thread trick, that seems to help on at least some windows systems to get a reliable sleep game loop…

Are you suggesting that it is possible to get a ‘stable’ frame rate in ANY system? If so I have never seen it – indy games or professional. Framerate will always jump around. You literally cannot run at exactly 60 fps. If frame rate makes your game ‘laggy’ then you are frame-locking your rendering logic, which is WRONG to begin with, as any FPS under the ‘intended’ will slow the game down, vs making it choppy. All movement and animation should be done based on time passed, not frames passed.

Nope. I don’t think it will be possible to get a stable timestep (lets not call it framerate anymore) on ANY system, just on some more systems. I didn’t want to emphasis the use of Thread.yield(), I just wanted to point out, that you were exeggarating in your statement.

Btw. a tight loop with Thread.sleep(1) along with the deamon-trick seems to be the right tradeoff between CPU usage and accuracy.

Regarding the frame-locking - there is also a lot of threads about fixed vs. variable timestep game loops and the consensus seems to be: use the one you think fits best in your targetted environment - if framelocking appears either switch the method or optimize performance :wink: