Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile identifier in java

I dont understand those few statements that I read:

because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");

What does it mean, I cant read-update-write?

When will I want to use volatile instead of simple boolean. In C#, I remember that I could use a simple static bool to control when a thread starts and stops, but in java I need to use the identifier, "volatile":

> public class StoppableTask extends Thread {
  private volatile boolean pleaseStop;

  public void run() {
    while (!pleaseStop) {
      // do some stuff...
    }
  }

  public void tellMeToStop() {
    pleaseStop = true;
  }
}
like image 533
Dmitry Makovetskiyd Avatar asked Aug 29 '11 07:08

Dmitry Makovetskiyd


1 Answers

The sentence speaks about this example:

public class CounterClass {
   private volatile int counter;

   public int increment() {
       return counter++;
   }
}

Although the counter has volatile modifier, it is not guaranteed that if two threads access the increment() method that two different integers will be returned. Because the counter++ operation is not atomic. It is get, increment, return. It is possible that two threads call increment() at the same time and that the first thread is at the get phase and the second thread is at the get phase before the first thread is at the increment phase.

Summary: volatile doesn't guarantee atomicity or whatever. It just guarantees that when you access the variable, you will not receive an old cached value. But it doesn't guarantee any thread safety or atomicity.

like image 112
Petar Minchev Avatar answered Oct 16 '22 20:10

Petar Minchev