Jan Weber
Jan Weber

Reputation: 137

Thread stops itself

I've been searching for a solution for a long time, but I wasn't able to find one, so I'll ask my question here. I have a thread which is started when the program starts and supposed to be idle until it is enabled by the application. Simple code example:

private class UpdaterThread extends Thread {

    private static final int UPDATE_RATE = 50;
    private Timer updateTimer = new Timer();

    private boolean enabled;

    public void run() {

        while (!closeRequested) {

            // If this is uncommented, the thread works as it's supposed to.
            // System.out.print("");

            if (enabled) {

                Snapshot next = getNextSnapshot(1f / UPDATE_RATE);
                System.out.println("Got next Snapshot");
                updateTimer.sync(UPDATE_RATE);
                System.out.println("Push");
                currentSnapshot = next;
            }
        }
    }

    public void enable() {

        enabled = true;
    }

    public void disable() {

        enabled = false;
    }
}

Upvotes: 0

Views: 1136

Answers (2)

Rock48
Rock48

Reputation: 92

since run() is called when the thread is started, you could just wait until later in the program to start it, also threads do not extend "Thread" but implements "Runnable" so the class definition would look like:

public class UpdaterThread implements Runnable

hope it helps :D

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533510

When you read a variable, which the JIT believes you didn't modify, it inlines the value. If you then modify the value later, it is too late, the value has been embedded in the code.

A simple way to avoid this is to use volatile but you would still have the problem than the thread is busy waiting for the value to change and there doesn't appear to be a good reason to do this. Another option is to add code which confuses the JIT do it doesn't do this optimisation. An empty synchronized block is enough but a friendlier way is to use Thread.sleep() which at least doesn't use up all your CPU.

I suggest using a volatile fields and sleeping with a period of 10-100 ms. However a simpler option is to not start the thread until it is needed.

Upvotes: 3

Related Questions