Volatile identifier in java

I do not understand the few statements that I read:

since access to a mutable variable never blocks, this is not suitable for cases when we want to read-update-write as atomic (if we are not ready to "skip updating");

What does it mean, I can’t read-update-write?

When I want to use volatile instead of a 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;
  }
}
+5
source share
2 answers

The sentence talks about this example:

public class CounterClass {
   private volatile int counter;

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

counter volatile, , increment(), . counter++ . get, increment, return. , increment() get, get, increment.

: volatile - . , . .

+11

volatile

FWIW volatile:

  • ( "" )
  • ( " " )
  • "volatile bean"
  • ( " " )

, :
https://farm4.static.flickr.com/3073/3035268779_f8a9dce89d.jpg
ready . , , , --

  • : Java.

    " ready, . , , . , , Thread 1, , Thread 2 , true ready."

+2

All Articles