Dummy statement needed, else code won't run

Can anyone figure out why the code below only works if I add a dummy statement in the loop? Sleep(0) also works, but without any statement it simply wont run (ie. the update method on the updatable isn’t called), no errors are given.

The ticking boolean is always true (insterted if i ever wish to pause the routine), updateNextCycle and msPassed are set by the main game loop. (the reason this is in a thread is because I don’t want the game loop to wait for the update method to complete. Busy is used to indicate to the main loop that the previous update isn’t ready yet).


    @Override
    public void run() {
        while(ticking) {
            int i = 0; //@todo figure out why this is needed
            if (updateNextCycle) {
                busy = true;
                updateNextCycle = false;
                updatable.update(msPassed);
                busy = false;
            }
        }
    }

This seems like a very odd way to structure things, for one your thread is going to sit in a tight loop needlessly consuming CPU cycles. Its not apparent what your intentions are so I assume you want it this way, however as you mention you have a separate thread that runs the main game loop I would suggest that this is not a good idea. I would put your problem down to a threading issue, is updateNextCycle declared volatile? How are you modifying it from the main game thread?

You probably eat up all the available cpu on a single cpu system or the loop completely runs in the cache of a multi-cpu system. As dbotha points out, you must either synchronize access to variables from multiple threads or declare all your shared flags volatile. The latter afaik only realiably works for booleans and only from java 1.5 onwards.

Refer to some documentation about thread safety like e.g. this http://www.javamex.com/tutorials/threads/thread_safety.shtml

In the future the updatable will be on another machine and the method is called through RMI (i know, not the best idea, but the assignment was to write a multiplayer game using RMI). I don’t want the game loop to wait for a failing RMI call, so that’s why all this is in a separate thread. The thread has a setter to change updateNextCycle which first checks if (!busy).

But you’re right about the locked CPU thing. I didn’t really think this through :slight_smile: Anyway, it works now, ty :slight_smile:

It’s still a good idea to have your thread yield/sleep when you don’t need it to be going full blast. Otherwise, you’re going to use 100% of the CPU when you don’t need it.

With RMI, you can sleep on the remote machine :slight_smile: