0

I tried running the code to the accepted answer to this question and it runs indefinitely on my machine. What is going on under the hood that causes this behavior? i.e. what is one thread seeing that the other thread is not? People talk about a 'cache' that is not flushed to main memory but where is this cache? Is it located in the JVM, is it the CPU memory cache or could it be a CPU register?

Shane
  • 2,271
  • 3
  • 27
  • 55

1 Answers1

0

As explained in the question you pointed out, the variable without the volatile keyword may be optimized in any way by the compiler,JIT, processor, so that there is no read from the shared memory. So the variable may be stored in a CPU register for the thread and it ends with having two separate variables (one by thread) having different values.

This explains why the volatile keyword is useful. This very same piece of code may or may not work as expected without this keyword.

The where is the cache question is difficult to answer since I think, there is no good answer. It may be on any layer.

Edit: the link posted by @polygnome in comment is great. You should definitely read it.

Xvolks
  • 2,065
  • 1
  • 21
  • 32
  • Thanks very much for your answer. I think @polygnome has removed his comment, would you mind adding the link you mentioned? – Shane Oct 02 '17 at 00:21
  • You question was flagged as already answered with a link. Check that link. – Xvolks Oct 02 '17 at 05:50