-4

If we have volatile variable, we are guaranteed that if we have two threads and the two threads read they will get the value from the main memory,also if we write and then a read happens we will get in the read the changes, but what are guaranteed and not guaranteed when we have many threads reading and writing on the volatile variable?

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
Nick T.
  • 1
  • 1

1 Answers1

0

NO. volatile won't do that.

Volatile: Almost Useless for Multi-Threaded Programming

There is a widespread notion that the keyword volatile is good for multi-threaded programming. I've seen interfaces with volatile qualifiers justified as "it might be used for multi-threaded programming". I thought was useful until the last few weeks, when it finally dawned on me (or if you prefer, got through my thick head) that volatile is almost useless for multi-threaded programming. I'll explain here why you should scrub most of it from your multi-threaded code.

...

There may be languages where it may have such an effect, but in C, the answer is an emphatic NO.

EDIT:

Now that the language is specified as Java, the answer is different, since Java implements its own memory model, and the volatile keyword does have a significant impact. See Do you ever use the volatile keyword in Java? and many other questions.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
  • OP indicated language is Java which does implement [memory barriers for volatile](https://stackoverflow.com/questions/13688697/is-a-write-to-a-volatile-a-memory-barrier-in-java). – Vasan Mar 21 '18 at 21:38
  • @Vasan Thanks. OP should have tagged his question with the Java tag, then. – Andrew Henle Mar 21 '18 at 22:08