girish babu
girish babu

Reputation: 21

Threads, Object state

Class A{

private boolean connected = false;

public void doAction(){

if(connected){
//do something
}
else{
//do this
  }
   }

public void setConnected(boolean flag)
    {
       this.connected = flag;
    }
  }

I have above code in my project and it is a singleton. setConnected() method will be triggered upon some condition(it will be triggered only once). doAction() method is invoked periodically by the scheduler for performing some operations.

My question is if the state of the singleton object is modified after construction( by calling setConnected()), the updated state is visible to the further invoking method calls (periodical invocation of doAction())?(note: the connected variable is not volatile).

Upvotes: 2

Views: 74

Answers (1)

Amit Bera
Amit Bera

Reputation: 7315

Your connected variable is not volatile that means, it does not guarantee that all other thread get updated value after any write operation by some other thread. So I will recommend using volatile for your use case. volatile keyword ensures all thread see the most recent updated value.

Edited:

A non-volatile variable also can be refreshed on the CPU cache in different condition.

  1. A thread can also be swapped out of its CPU forcing it to reload it cache memory when it gets the next time slice.

  2. A thread flushes all of its updated value when it exit / or finished.If you are creating a new thread (to call doAction) after the thread (which called your setConnected method) and it successfully finished it will get the updated value as a new thread will create a new context for it every time.

Upvotes: 2

Related Questions