SlideShare a Scribd company logo
1 of 26
Download to read offline
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!

More Related Content

What's hot (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
 

Viewers also liked

Java gc
Java gcJava gc
Java gcNiit
 
Java GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuningekino
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Anna Shymchenko
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyDhanu Gupta
 
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 contextTomek Borek
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimizationRajan Jethva
 
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 GCKelum Senanayake
 
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 issuesSergey Podolsky
 
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 PresentationLudovic Poitou
 
淺談 Java GC 原理、調教和 新發展
淺談 Java GC 原理、調教和新發展淺談 Java GC 原理、調教和新發展
淺談 Java GC 原理、調教和 新發展Leon Chen
 
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 9Poonam Bajaj Parhar
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage CollectionHaim Yadid
 

Viewers also liked (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
 

Similar to Java Memory Model

Similar to 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
 
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
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 

More from *instinctools

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*instinctools
 
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*instinctools
 
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*instinctools
 
CRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANYCRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANY*instinctools
 
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*instinctools
 
How to protect sensitive data
How to protect sensitive dataHow to protect sensitive data
How to protect sensitive data*instinctools
 
Video streaming trends & technologies
Video streaming trends & technologiesVideo streaming trends & technologies
Video streaming trends & technologies*instinctools
 
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*instinctools
 
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...*instinctools
 
Top software development trends of 2021
Top software development trends of 2021Top software development trends of 2021
Top software development trends of 2021*instinctools
 
6 hidden costs of cloud migration
6 hidden costs of cloud migration6 hidden costs of cloud migration
6 hidden costs of cloud migration*instinctools
 
Learning management system
Learning management systemLearning management system
Learning management system*instinctools
 
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*instinctools
 
Business Analysis in IT
Business Analysis in ITBusiness Analysis in IT
Business Analysis in IT*instinctools
 
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!*instinctools
 
Videostream compression in iOS
Videostream compression in iOSVideostream compression in iOS
Videostream compression in iOS*instinctools
 
Apple Watch (Part 2)
Apple Watch (Part 2)Apple Watch (Part 2)
Apple Watch (Part 2)*instinctools
 
Apple Watch (Part 1)
Apple Watch (Part 1)Apple Watch (Part 1)
Apple Watch (Part 1)*instinctools
 

More from *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
 

Recently uploaded

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Recently uploaded (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

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!