Confused about instance initialization

shakeshuck

I have a class, such as:

public class Test {

    private static Thread aThread;
    private static Loopy aLoop;

    public Test() {
    }

    public static void main(String[] args) {

        startUpdate();
        stopUpdate();
        startUpdate();

    }

    public static void startUpdate() {

        aLoop = new Loopy();
        aThread = new Thread(aLoop);

        aThread.start();

    }

    public static void stopUpdate() {

        if (aThread != null) {
            aLoop.finish();
        }
    }
}

with runnable code that looks like:

public class Loopy implements Runnable {

    private static String status = "R";       // Run

    public void run() {

        while (status.equals("R")) {
            // Do Stuff
        }
    }

    public void finish() {
        status = "F";                         // End Run
    }
}

Calling startUpdate works the first time.

StopUpdate works as planned.

Calling startUpdate the second time results in no work being done as status is still equal to "F" from the stop, even though I am starting a new instance of Loopy which (to me) should have the default value of "R".

Is the status persisting across instances, or have I made an error I haven't spotted yet?

Boris the Spider

You have overused static.

In your Loopy class the String status is static and is therefore shared across all Loopy instances.

You should make status an instance variable by removing the static.

Another note is that status should also be volatile as it's state is changed by numerous threads without synchronization.

I would also suggest that maybe you should make all the variables/methods in Test instance too (except main) as it's generally best to avoid static where possible:

public class Test {

    private Thread aThread;
    private Loopy aLoop;

    public static void main(String[] args) {
        final Test test = new Test();
        test.startUpdate();
        test.stopUpdate();
        test.startUpdate();

    }

    public void startUpdate() {
        aLoop = new Loopy();
        aThread = new Thread(aLoop);
        aThread.start();
    }

    public void stopUpdate() {
        if (aThread != null) {
            aLoop.finish();
        }
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related