SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Java Memory Model
Java Memory Model
Java Memory Model is the model that describes the
behavior of memory in Java program.
The main task of this model is to reply the question that
can distinguish the concrete definition of «read» in the
program.
Java Memory Model
In the case of single-threaded languages usually the memory
pattern is quite simple:
That is why the memory model is often understood as the
model of memory behavior pattern in multi-threaded
applications. But in some cases it is required also for judging
about the pattern of single-threaded applications.
int x = 10;
int b = x;
int c = b + x;
x = c — b;
c = b;
Java Memory Model
In order to develop a multi-threaded application we
need to understand:
●
In what order the actions are executed in the application;
●
How does the data sharing between threads?
Java Memory Model: Access atomicity
We would like to make every action at the field
atomic:
long value = 0;
value = -1; System.out.println(value);
// 0, -1,
// 0xFFFFFFFF00000000 | 18446744069414584000
Java Memory Model: Access atomicity
In order to provide atomicity, we need to have this
support from hardware.
Possible problems:
– The absence of hardware operations for read/record of big values;
– The request to memory’s sub-system, for example, at х86 you can’t
place the data point at crossing of cashlines.
Java Memory Model: Access atomicity
In the current version of JMM we can see that the
work with all primitives except long/double has to
be atomic by default. For the activation of atomicity
of long/double it is required to use volatile.
Java Memory Model: Word tearing
We would like to make all operations at fields/array
elements/etc. to be independent:
int[] array = new int[4]; array[0] = 1; array[1] = 1;
array[0] = 2; array[1] = 2;
int a1 = array[0];
int a2 = array[1];
System.out.println(a1 == a2);
<term> <term> <join both>
Java Memory Model: Word tearing
To provide the independent read/record, unexpectedly we
need to have the same kind of support from hardware.
Possible problems:
– The absence of hardware operations for read/record of too small
data points. Usually this is for N < 8 bit.
Solution:
– The minimal data type has to be N >= 8 bit and then we can make
independent read/record for all types of data.
Java Memory Model: Word tearing
We wonder what will happen in such a case?
BitSet bitSet = new BitSet();
bitSet.set(1); bitSet.set(2);
boolean b1 = bitSet.get(1);
boolean b2 = bitSet.get(2);
System.out.println(b1 == b2);
<term> <term> <join both>
Java Memory Model: Reordering
We would like all actions in the program to be executed in the
same order as the one written by a programmer in the initial
code. But some types of optimization require certain changes:
int x = 0; int y = 0;
x = 10;
println(y);
y = 20;
println(x);
println(20); println(10);
...
Java Memory Model: Reordering
int x = 0; int y = 0;
int v1 = x;
int v2 = y;
y = 20;
x = 10;
int v2 = y;
int v1 = x;
y = 20;
x = 10;
int x = 0; int y = 0;
Runtime and iron don’t have the All-Seeing Eye to find what
changes never break the logics globally, they can define
correctness only of the local order — Program Order.
Java Memory Model: Synchronization Actions
JMM allows multiple types of optimization with appliance of
shifts and offers the set of SA for limiting this:
●
volatile read/write
●
lock/unlock monitor
●
first/last action in the thread
●
the action that launches the thread
●
the action that finds the interrupted thread (Thread.join().
Thread.isInterrupted(),etc.)
Java Memory Model: Synchronization Actions
JMM forbids to change the work order with SA. That’s why we
can say for sure in what order the actions at SA elements
happen in this example:
volatile int x = 0; volatile int y = 0;
y = 5;
println(x);
x = 5;
println(y);
Java Memory Model: Synchronization Actions
volatile int x = 0; volatile int y = 0;
y = 5;
println(x);
x = 5;
println(y);
Also SA elements help to connect the sequences of actions
between different threads, in such way forming
Synchronization Order:
Java Memory Model: Happens Before
But let’s examine the case, when we have actions not only at
SA elements, what will happen with x?
int x = 0; volatile int y = 0;
int v1 = y;
int v2 = x;
x = 5;
y = 5;
Java Memory Model: Happens Before
Right now let’s examine the case, when reading of v1 have
identified 5 in y, then Happens Before works in such way,
when v2 equals 5:
int x = 0; volatile int y = 0;
int v1 = y;
int v2 = x;
x = 5;
y = 5;
Java Memory Model: Happens Before
Right now let’s examine the case when v1 read in y - 0, in this
case v2 can be equal whether 0 or 5:
int x = 0; volatile int y = 0;
int v1 = y;
int v2 = x;
x = 5;
y = 5;
Java Memory Model: Happens Before
Now focus on another case:
volatile int a = 0; int b, c, d, e;
b = 1;
c = 2;
a = 5;
d = 3;
e = 4;
int v1 = d;
int v2 = e;
int v3 = a;
int v4 = b;
int v5 = c;
Java Memory Model: Happens Before
Let’s take a closer look at one more case:
volatile int a = 0, b; int c, d, e, g;
c = 1;
d = 2;
a = 3;
int v1 = b;
int v2 = e;
int v3 = g;
e = 4;
g = 5;
b = 6;
int v1 = a;
int v2 = c;
int v3 = d;
Java Memory Model: Happens Before
public class С<T> {
private T val;
public synchronized void setVal(final T val) {
if(this.val == null) this.val = val;
}
public synchronized T getVal() {
return val;
}
}
Java Memory Model: Happens Before
public class С<T> {
private T val;
public synchronized void setVal(final T val) {
if(this.val == null) this.val = val;
}
public T getVal() {
return val;
}
}
Java Memory Model: Happens Before
public class С<T> {
static volatile int BARRIER; int sink;
private T val;
public synchronized void setVal(final T val) {
if(this.val == null) this.val = val;
}
public T getVal() {
sink = BARRIER;
return val;
}
}
Java Memory Model: Happens Before
public class С<T> {
private volatile T val;
public synchronized void setVal(final T val) {
if(this.val == null) this.val = val;
}
public T getVal() {
return val;
}
}
Java Memory Model: Happens Before
public class C<T> {
private T val;
public synchronized void setVal(final T val) {
if(val == null) {
VarHandle.releaseFence();
this.val = val;
VarHandle.fullFence();
}
}
public T getVal() {
T val = this.val;
VarHandle.acquireFence();
return val;
}
}
May The Force Be With You!

Contenu connexe

Tendances

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
myrajendra
 

Tendances (20)

Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Core java
Core javaCore java
Core java
 
Core java
Core java Core java
Core java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 

En vedette

Java gc
Java gcJava gc
Java gc
Niit
 
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 PresentationGC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
Ludovic Poitou
 

En vedette (20)

Java gc
Java gcJava gc
Java gc
 
Java GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuning
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- Study
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Java Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and contextJava Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and context
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimization
 
What you need to know about GC
What you need to know about GCWhat you need to know about GC
What you need to know about GC
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Java GC, Off-heap workshop
Java GC, Off-heap workshopJava GC, Off-heap workshop
Java GC, Off-heap workshop
 
How long can you afford to Stop The World?
How long can you afford to Stop The World?How long can you afford to Stop The World?
How long can you afford to Stop The World?
 
JVM及其调优
JVM及其调优JVM及其调优
JVM及其调优
 
Tuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issuesTuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issues
 
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 PresentationGC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
 
淺談 Java GC 原理、調教和 新發展
淺談 Java GC 原理、調教和新發展淺談 Java GC 原理、調教和新發展
淺談 Java GC 原理、調教和 新發展
 
Java GC
Java GCJava GC
Java GC
 
Let's Learn to Talk to GC Logs in Java 9
Let's Learn to Talk to GC Logs in Java 9Let's Learn to Talk to GC Logs in Java 9
Let's Learn to Talk to GC Logs in Java 9
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage Collection
 

Similaire à Java Memory Model

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 

Similaire à Java Memory Model (20)

Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Java
JavaJava
Java
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Memory model
Memory modelMemory model
Memory model
 
Core java day1
Core java day1Core java day1
Core java day1
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 

Plus de *instinctools

Plus de *instinctools (20)

ERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media CompanyERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media Company
 
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdfIntegration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
 
Examples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdfExamples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdf
 
CRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANYCRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANY
 
BI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry CorporationBI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry Corporation
 
How to protect sensitive data
How to protect sensitive dataHow to protect sensitive data
How to protect sensitive data
 
Video streaming trends & technologies
Video streaming trends & technologiesVideo streaming trends & technologies
Video streaming trends & technologies
 
Happy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbersHappy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbers
 
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
 
Top software development trends of 2021
Top software development trends of 2021Top software development trends of 2021
Top software development trends of 2021
 
6 hidden costs of cloud migration
6 hidden costs of cloud migration6 hidden costs of cloud migration
6 hidden costs of cloud migration
 
Learning management system
Learning management systemLearning management system
Learning management system
 
P2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity providerP2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity provider
 
Business Analysis in IT
Business Analysis in ITBusiness Analysis in IT
Business Analysis in IT
 
Java NIO.2
Java NIO.2Java NIO.2
Java NIO.2
 
Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!
 
Videostream compression in iOS
Videostream compression in iOSVideostream compression in iOS
Videostream compression in iOS
 
Apple Watch (Part 2)
Apple Watch (Part 2)Apple Watch (Part 2)
Apple Watch (Part 2)
 
Apple Watch (Part 1)
Apple Watch (Part 1)Apple Watch (Part 1)
Apple Watch (Part 1)
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 

Dernier

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Dernier (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Java Memory Model

  • 2. Java Memory Model Java Memory Model is the model that describes the behavior of memory in Java program. The main task of this model is to reply the question that can distinguish the concrete definition of «read» in the program.
  • 3. Java Memory Model In the case of single-threaded languages usually the memory pattern is quite simple: That is why the memory model is often understood as the model of memory behavior pattern in multi-threaded applications. But in some cases it is required also for judging about the pattern of single-threaded applications. int x = 10; int b = x; int c = b + x; x = c — b; c = b;
  • 4. Java Memory Model In order to develop a multi-threaded application we need to understand: ● In what order the actions are executed in the application; ● How does the data sharing between threads?
  • 5. Java Memory Model: Access atomicity We would like to make every action at the field atomic: long value = 0; value = -1; System.out.println(value); // 0, -1, // 0xFFFFFFFF00000000 | 18446744069414584000
  • 6. Java Memory Model: Access atomicity In order to provide atomicity, we need to have this support from hardware. Possible problems: – The absence of hardware operations for read/record of big values; – The request to memory’s sub-system, for example, at х86 you can’t place the data point at crossing of cashlines.
  • 7. Java Memory Model: Access atomicity In the current version of JMM we can see that the work with all primitives except long/double has to be atomic by default. For the activation of atomicity of long/double it is required to use volatile.
  • 8. Java Memory Model: Word tearing We would like to make all operations at fields/array elements/etc. to be independent: int[] array = new int[4]; array[0] = 1; array[1] = 1; array[0] = 2; array[1] = 2; int a1 = array[0]; int a2 = array[1]; System.out.println(a1 == a2); <term> <term> <join both>
  • 9. Java Memory Model: Word tearing To provide the independent read/record, unexpectedly we need to have the same kind of support from hardware. Possible problems: – The absence of hardware operations for read/record of too small data points. Usually this is for N < 8 bit. Solution: – The minimal data type has to be N >= 8 bit and then we can make independent read/record for all types of data.
  • 10. Java Memory Model: Word tearing We wonder what will happen in such a case? BitSet bitSet = new BitSet(); bitSet.set(1); bitSet.set(2); boolean b1 = bitSet.get(1); boolean b2 = bitSet.get(2); System.out.println(b1 == b2); <term> <term> <join both>
  • 11. Java Memory Model: Reordering We would like all actions in the program to be executed in the same order as the one written by a programmer in the initial code. But some types of optimization require certain changes: int x = 0; int y = 0; x = 10; println(y); y = 20; println(x); println(20); println(10); ...
  • 12. Java Memory Model: Reordering int x = 0; int y = 0; int v1 = x; int v2 = y; y = 20; x = 10; int v2 = y; int v1 = x; y = 20; x = 10; int x = 0; int y = 0; Runtime and iron don’t have the All-Seeing Eye to find what changes never break the logics globally, they can define correctness only of the local order — Program Order.
  • 13. Java Memory Model: Synchronization Actions JMM allows multiple types of optimization with appliance of shifts and offers the set of SA for limiting this: ● volatile read/write ● lock/unlock monitor ● first/last action in the thread ● the action that launches the thread ● the action that finds the interrupted thread (Thread.join(). Thread.isInterrupted(),etc.)
  • 14. Java Memory Model: Synchronization Actions JMM forbids to change the work order with SA. That’s why we can say for sure in what order the actions at SA elements happen in this example: volatile int x = 0; volatile int y = 0; y = 5; println(x); x = 5; println(y);
  • 15. Java Memory Model: Synchronization Actions volatile int x = 0; volatile int y = 0; y = 5; println(x); x = 5; println(y); Also SA elements help to connect the sequences of actions between different threads, in such way forming Synchronization Order:
  • 16. Java Memory Model: Happens Before But let’s examine the case, when we have actions not only at SA elements, what will happen with x? int x = 0; volatile int y = 0; int v1 = y; int v2 = x; x = 5; y = 5;
  • 17. Java Memory Model: Happens Before Right now let’s examine the case, when reading of v1 have identified 5 in y, then Happens Before works in such way, when v2 equals 5: int x = 0; volatile int y = 0; int v1 = y; int v2 = x; x = 5; y = 5;
  • 18. Java Memory Model: Happens Before Right now let’s examine the case when v1 read in y - 0, in this case v2 can be equal whether 0 or 5: int x = 0; volatile int y = 0; int v1 = y; int v2 = x; x = 5; y = 5;
  • 19. Java Memory Model: Happens Before Now focus on another case: volatile int a = 0; int b, c, d, e; b = 1; c = 2; a = 5; d = 3; e = 4; int v1 = d; int v2 = e; int v3 = a; int v4 = b; int v5 = c;
  • 20. Java Memory Model: Happens Before Let’s take a closer look at one more case: volatile int a = 0, b; int c, d, e, g; c = 1; d = 2; a = 3; int v1 = b; int v2 = e; int v3 = g; e = 4; g = 5; b = 6; int v1 = a; int v2 = c; int v3 = d;
  • 21. Java Memory Model: Happens Before public class С<T> { private T val; public synchronized void setVal(final T val) { if(this.val == null) this.val = val; } public synchronized T getVal() { return val; } }
  • 22. Java Memory Model: Happens Before public class С<T> { private T val; public synchronized void setVal(final T val) { if(this.val == null) this.val = val; } public T getVal() { return val; } }
  • 23. Java Memory Model: Happens Before public class С<T> { static volatile int BARRIER; int sink; private T val; public synchronized void setVal(final T val) { if(this.val == null) this.val = val; } public T getVal() { sink = BARRIER; return val; } }
  • 24. Java Memory Model: Happens Before public class С<T> { private volatile T val; public synchronized void setVal(final T val) { if(this.val == null) this.val = val; } public T getVal() { return val; } }
  • 25. Java Memory Model: Happens Before public class C<T> { private T val; public synchronized void setVal(final T val) { if(val == null) { VarHandle.releaseFence(); this.val = val; VarHandle.fullFence(); } } public T getVal() { T val = this.val; VarHandle.acquireFence(); return val; } }
  • 26. May The Force Be With You!