Search code examples
javamultithreadingthrowable

Java - Thread Stops Without Any Indication


I have a weird issue, where I'm trying to make a program which is using a thread to implement a tick update system, using the following code:

@Override
public void run(){
    long lastTime = System.nanoTime();
    long deltaTime;
    float passedTime = 0;
    long ticks = 0;

    while(true){
        long currentTime = System.nanoTime();

        deltaTime = currentTime - lastTime;
        lastTime = currentTime;

        passedTime += deltaTime / tickTime;

        if(passedTime * 20 > ticks){
            ticks++;
            tick();

            System.out.println(ticks);
        }
    }
}

This works fine, except for the fact that after exactly 161 ticks it simply ceases to run, it doesn't throw anything, no exceptions, no errors, nothing. However as soon as I do the following:

@Override
public void run(){
    long lastTime = System.nanoTime();
    long deltaTime;
    float passedTime = 0;
    long ticks = 0;
    long useless = 0;

    while(true){
        long currentTime = System.nanoTime();

        deltaTime = currentTime - lastTime;
        lastTime = currentTime;

        //Don't focus on this bit, I know it's a bit odd.
        passedTime += deltaTime / tickTime;

        if(passedTime * 20 > ticks){
            ticks++;
            tick();

            System.out.println(ticks);
        }

        useless++;
        System.out.print(useless);
    }
}

And now suddenly it runs with no problem?

Does anyone have any idea what this could be due to? Thanks in advance!


Solution

  • The reason adding just a print statement fixes the iussue is because you are spinning.

    If a thread performs a tight loop with no blocking/io/other it will just spin and hog the cpu, causing all other polite threads to get fewer resources.

    To get around this (as a temporary measure) you could add a Thread.sleep(0) which will release the cpu for other threads to get cpu time.

    A more permanent solution should be to put together some mechanism to communicate between your process (perhaps a BlockingQueue) so your thread spends most of it's time waiting/blocking.