Answer the question
In order to leave comments, you need to log in
@Volatile, caching?
I don’t fully understand what caching means and how @Volatile works, I know that when using the volatile annotation on a variable, the value of the variable is read by reference to this variable from different threads, and not from the thread cache, but I don’t quite understand what kind of cache , where it is and how to track that the value is cached. I have a feeling that the question is very stupid, but I can’t leave it unresolved :(
In simple words, please explain.
Answer the question
In order to leave comments, you need to log in
CPUs have caches of different levels L1, L2, L3. Each thread (as well as the processor core) has its own cache. These caches store the minimum set of RAM to ensure performance. If a variable is defined as volatile, then all write operations on it are immediately reflected in memory and are not cached. Threads do not have a local copy of memory, and part of the data that a thread reads / writes may be from the cache, and not from main memory, and therefore when one thread changes a variable, the other thread cannot see the changes on it. Roughly speaking, for such cases, volatile is needed. Phew, I explained as best I could, maybe someone will explain in more detail.
You can read about the memory model in Java
https://docs.oracle.com/javase/specs/jls/se7/html/...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question