Question

I am trying to pass a variable to another class but my getter won't send the updated value of my variable it sends the value I used to initialize it.

Main class:

    OtherClass otherclass = new OtherClass(new Main());
    private boolean updateVar = true
    private int timer = 0;

    public void tick(){

        if(updateVar == true) timer++;
    }

    public int getTimer(){

        return timer;
    }

Other Class:

    Main main;
    private int holdTimer;

    public OtherClass(Main main){

       this.main = main;
       holdTimer = this.main.getTimer();

          System.out.println(holdTimer);
    }

Every time it comes out as 0, Can anyone help? My tick() is being called by my thread every second in case you were wondering.

Was it helpful?

Solution

Because you are calling tick() in another thread, you have entered the dark world of concurrency and thread safety.

Put simply, changes made in one thread are not necessarily visible to other threads, unless you follow some strict rules:

  • make the field volatile
  • all access to it must be synchronized

Ergo:

private volatile int timer = 0;

public synchronized void tick(){
    if(updateVar == true) timer++;
}

pubic synchronized int getTimer(){
    return timer;
}

You may also have to join() the updating thread to wait for it to complete if you are not in a wait loop in the main thread.

OTHER TIPS

You need to call tick() if you want the member variable incremented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top