-1

it is said that volatile variables can be used to achieve synchronization. However, volatile variables are still susceptible to memory consistence errors. Why this is so?

Bawantha
  • 3,644
  • 4
  • 24
  • 36
  • Huh? Can you be more specific? What errors specifically? If you're just asking "what are all the problems that can arise from using only volatile for all synchronization," that's too broad for SO. – yshavit Oct 27 '17 at 17:48
  • 1
    You many want to read about the [difference between volatile and synchronized](https://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java). – azurefrog Oct 27 '17 at 17:50

2 Answers2

2

Volatile is irrelevant to the synchronization.

Volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

Here is the link to JavaDoc

DontPanic
  • 1,327
  • 1
  • 13
  • 20
  • One needs to be a bit careful with terminology in this area. The happens-before relationship you refer to is due to what the JLS calls "[synchronization](https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.4)." The term is overloaded, and I'm not sure which version the OP is referring to (or whether they recognize that it's overloaded). – yshavit Oct 27 '17 at 19:23
0

No volatile variables themselves are not subject to memory consistency errors. The volatile variables establish the memory barrier and respect the happens before relationship, so write is flushed to main memory, so that reads are consistent. It's the operations that need to be atomic.

Assuming i is int.

i=10 is ok

i++ is not atomic, it amounts to reading the current value incrementing it and then pushing it.

For boolean variables the only sensible operation is assignment of value , thus they can be used consistently.

Again its the operations that need to be atomic.

Ramandeep Nanda
  • 519
  • 3
  • 9
  • 1
    "For boolean variables the only sensible operation is assignment of value , thus they can be used consistently." What about `b = !b`? Isn't that analogous to `i++`? – yshavit Oct 30 '17 at 14:37
  • @yshavit Nice catch yshavit. well use locks then, again it has nothing to do with memory consistency. – Ramandeep Nanda Oct 30 '17 at 14:41
  • Quite true. It's still not clear to me what the OP was actually asking about, unfortunately. In particular, it's not clear to me whether they're referring to word tearing or something else. – yshavit Oct 30 '17 at 14:54