1

I was asked by interviewer is there any danger not to use volatile if we know for sure that threads will never interfere.

eg. we have:

int i = 10; 
// Thread 1 
i++; 
// await some time and switch to Thread 2
getI();

I don't use any synchronization.
Do we have any danger to receive outdated value of i by second thread?

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • This question would be useful to understand volatile concepts: http://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java/34355995#34355995 – Ravindra babu Feb 12 '16 at 15:56

3 Answers3

4

Without volatile or synchronized or read/write barrier, there is no guarantee that another thread will ever see a change you made, no matter how long your wait. In particular boolean fields can be inlined into the code and no read actually performed. In theory, int values could be inlined if the JVM detects the field is not changed by the thread (I don't believe it actually does though)

we know for sure that threads will never interfere.

This is not something you can know, unless the reading thread is not running when you perform the update. When thread starts it will see any changes which occurred before it started.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

You might receive outdated values, yes.

The reason in short is:

Every thread in Java has its own little 'cache'. For performance reasons, threads keep a copy of the 'master' data in their own memory. So you basically have a main memory and a threadlocal one. The volatile keyword forces the thread to access the main memory and not its local one.

Refer to this for more information: http://www.ibm.com/developerworks/library/j-5things15/

Slomo
  • 1,224
  • 8
  • 11
  • 1
    Note: accessing volatile rarely means you would hit main memory, as this would be a performance hit. However, it ensure you would see a consistent value. In fact this is implemented in hardware by the L2 cache in the cores talking to each other directly via a special bus. i.e. it might not even hit the L3 cache. – Peter Lawrey Feb 12 '16 at 14:39
1

If an interviewer asked me that question, I would answer in terms of the Java Language Specification. There is no "cache" or "main memory" in the JLS. The JLS talks about fields (a.k.a., instance variables and class variables) and it makes very specific guarantees about when an update to a field that happens in thread A will become visible in thread B. Implementation details like "cache" and "memory barriers" and can vary from one platform to another, but a program that is correct with respect to the JLS should (in theory) be correct on any Java platform.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57