The Internal Java Memory Model
The Java memory model used internally in the JVM divides memory between thread stacks and the heap. This diagram illustrates the Java memory model from a logic perspective:

Each thread has a thread stack. A thread Stack is a memory area which can only be access by the thread that owns the thread stack.
Heap can be accessed by all threads. So in case you need to shrare data between threads. It has to be shraed via heap.
Thread Stack
- Local variables
- byte, short char, int, long, float, double
- Referenes to Objects
Heap
- Objects
멤버변수 (필드)로 선언되면 쓰레드 간 공유 가능




To sum up, in order to be sure that you avoid race conditions and that writes are always visible to other threads, then you need to use the synchronized blocks or use the volatile key word for variable.
Java Happens Before Guarantee - Java Memory Model - Part 2
Java Happens Before Guarantee A set of restrictions on instruction reordering to avoid instruction reordering breaking the Java visibility guarantees
Instruction Reordering
- CPUs execute multiple instructions in parallel

Instruction reordering may affect visibility of changes to objects shared between threads


Thread 1 call storeFrame, Thread 2 call takeFrame.
여기서 volatile 키워드 및 synchronization block의 활용이 전혀 없기 때문에 Thread 1 에서 저장한 Frame 필드가 Thread 2 에서 visible 하다는 보장이 없다.
visiblity를 보장하기 위해서는
- Thread 1 에서 write (store)한 Frame이 Main memory에 업데이트 되어야 한다.
- Thread 2 에서는 main memory에서 Frame 필드를 read (take)해야한다. 쓰레드 스택 주소의 필드를 읽지 X
결국 위의 naive 한 코드는 visiblity problem을 가지고 있다.

volatile
- if a field is volatile that means every write to the field will flushed directly to main memory
- similarly whenever a volatile field is read the value of the filed read directly from main memory

Instruction reordering may break the volatile visibility guarantee
CPU 1이 보았을때 store 1의 instruction을 reorder 해도 아무 상관이 없어보임
→ 그렇지 않다!
volatile 이 선언된 hasNewFrame = true를 먼저 호출하면 CPU 2 가 읽었을때 hasNewFrame은 true 이지만 frame은 null 혹은 이전에 set 된 frame일 수 있음

Volatile happens before guarantee
- volatile로 선언된 변수 앞에서 set 되는 instruction들은 volatile 필드를 write하는 instruction 앞으로 reordering 될 수 없다!
- 즉, this.hasNewFrame = ture이 무조건 제일 나중에 실행됨을 보장
- 반대로, 읽기의 경우에는 volatile 필드를 읽는 instruction은 가장 먼저 실행됨을 보장한다.
Synchronized visibility guarantee


when a thread enters a synchronized block, the thread will refresh all variables from main memory that are visible to the thread at that time
Instruction reorderingmay break the synchronized visibility guarantee

Synchronized happens before guarantee

동기화 블럭의 진입/ 퇴장의 순서를 재조정하는 instruction reordering 불가