Search code examples
javamultithreadingjava.util.concurrentatomicboolean

How to compare AtomicBoolean with boolean value in java


I'm trying to deploy TTAS in a multi-threading application in java, using this code:

AtomicBoolean state= new AtomicBoolean(false);
void lock(){
    while(true)
    {
      while(state.get())
      {
        if(!state.getAndSet(true))
        return;
      }
    }
}

but how can I compare the value of the state to check if it's true or false, when I try to spin on the it's value while I got each time an error saying that I'm trying to compare two different variables' type ? exp:

Lock lock = new Lock();
if(lock.state==true) // error ! 
{
   //do something
}

thank you!


Solution

  • but how can I compare the value of the state to check if it's true or false

    You just need to call get():

    if (lock.state.get())
    

    I'm confused as to why you didn't see this before though, given that you're already using it in your while loop:

    while(state.get())