SlideShare a Scribd company logo
1 of 26
The Java Memory Model Alexander Martens
Structure What is a memory model about? Platform memory models Annotation: Formal semantics Pro & Contra The new Java Memory Model (JMM) History Atomicity rules Ordering rules Visibility rules Piggybacking on synchronization Publication Initialization safety Changes Implementation sketch
What is a memory model about? A memory model defines the behavior of threads how to interact through shared mutual memory. Therefore you need rules for Atomicity: Which operations are atomic? Ordering: In which order do the operations happen? Visibility: When is the modified data visible to other processors? These depends on the memory model at processor level, because of the varying degrees of cache coherence across different architectures.
Platform memory models
Platform memory models defines what guarantees programs can expect from the memory Atomicity: Which operations are not interrupted by the scheduler? Ordering: In which situation are operations reordered to achieve maximum performance? Visibility: Which writes to shared mutual memory are visible to other processors at any given time? specifies memory barriers (special instructions of a processor) to enforce an ordering constraint Some processors exhibit a strong memory model, other processors exhibit a weaker memory model (different processors are able to see different values for the same memory location).
JMM and PMM JMM can be seen as an abstraction layer across different multiprocessor architectures. In dependence to the underlying hardware, the Java compiler deals with the differences by inserting memory barriers at the appropriate places to maintain the rules of the JMM.
Annotation: Formal semantics Together with the definition of single-threaded execution, the memory model specifies the formal semantics of a programming language. Typically, in a single-threaded environment the compiler is required to implement as-if-serial semantics. As-if-serial: All actions of a thread can be reordered for optimization, as long as the result is the same as if they are ordered in program order.
Pro & Contra Pro A programmer can reason about code execution. Atomicity and visibility is well-regulated. A data race can be prevented, because of ordering rules. A data race occurs, if a reads and writes of different threads on the same variable are not in a partial order. A compiler / processor is able to perform important optimizations, like loop fusion, in multi-threaded environment to achieve maximum performance. Contra The memory model also leads to performance cost, because of locks and other communication stuff.
History 1991: Oak was developed under the name "The Green Project" by James Goslip and other developers within 18 months. The project was initiated by Sun Microsystems to develop a kernel for executing safe, portable, object-oriented and multi-threaded software on set-top boxes.  1995: Java 1.0 has been published by Sun Microsystems.
History 2004: The original memory model was updated through the Java Community Process, as Java Specification Request 133, for Java 5.0, because the old one prevented many runtime optimizations and it didn’t provide enough guarantees for code safety.
Atomicity rules Accesses to variables of primitive types (excluding long and double) and reference variables are atomic. Accesses to volatile variables of primitive types (including long and double) and reference variables are atomic. Operations on atomic  variables in the package „java.util.concurrent.atomic“ are atomic, too.
Ordering rules JMM defines an happens-before partially order for all instructions in a multi-threaded program. The order guarantees: Thread B will see the result of Thread A, if there exists a happens-before relation between B and A (because of corresponding visibility rules). If there exists a happens-before relation, the order of instructions will be reordered at will.
Happens-before order Program order rule Monitor lock rule Volatile variable rule Thread start rule Thread termination rule Interruption rule Finalizer rule Transitivity
Visibility rules Thread rule Monitor lock rule Volatile variable rule Atomic variable rule Final variable rule
Piggybacking on synchronization Piggybacking on synchronization means combining the program order rule with the monitor lock rule or volatile variable rule concerning ordering and visibility of ordering and visibility, appearing in a code sequence. Pro:  Not every method must be synchronized.  Performance benefit A global order can be asserted by using a volatile variable as a guard.
Publication The absence of a happens-before order between publishing a shared object and accessing it leads to a partially constructed object. @NotThreadSafe public class UnsafeLazyInitialization{ 	private static Resource resource; 	public static Resource getInstance() { if (resource == null) 				resource = new Resource(); return resource; } }
Thread-safe lazy initilization Thread-safe lazy initialization is guaranteed by synchronization of the getInstance method. @ThreadSafe public class SafeLazyInitialization{ 	private static Resource resource; 	public synchronized static Resource getInstance() { if (resource == null) 				resource = new Resource(); return resource; } }
Double-checked locking Antipattern (not thread safe), invented to reduce the impact of synchronization. In the original JMM synchronization was expensive concerning performance. Since JRE 5.0 it’s obsolete, because of a tuned JVM (especially JMM). Now it’s better to use thelazy initialization holder class idiom to gain performance, because it offers the same benefit and is easier to understand.
Double-checked locking @NotThreadSafe public class DoubleCheckedLocking{ 	private static Resource resource; 	public static Resource getInstance() { if (resource == null) { 			synchronized (doubleCheckedLocking.class) { if (resource == null)  					resource = new Resource(); } } } }
Lazy initialization holder class idiom combines the safe lazy initialization with the lazy initialization holder class idiom does not require synchronization, because of eager class initialization idiom @ThreadSafe public class ResourceFactory{ 	private static class ResourceHolder{ 		public static Resource resource= new Resource(); } 	public static Resource getResource() { return ResourceHolder.resource; } }
Initialization safety Allows properly constructed immutable objects to be safely shared across threads without synchronization. Threads, obtaining a reference to that objects, are guaranteed to see up-to-date values of final fields. Initial writes aren’t reordered with accesses, coming after the final field is frozen.
Changes Accesses to volatile variables won’t be reordered with any other memory operation. useful for using a volatile variable as a guard static int a = 0, b = 0; static int x = 0, y = 0; static volatile boolean initialized =false;   //Thread A a = 1; b = 1; initialized =true;   //ThreadB while(!initialized){} x = a; y = b;
Changes Introduction of the happens-before order The initialization of final fields will never be reordered with operations following the finalization associated with the end of the constructor.  Final means final.
Implementation sketch Dependent on the underlying hardware platform model , the Java compiler insert the right memory barriers/fences, so that the Java memory model is valid.  In a general model, the following fences exist: LoadLoad StoreStore LoadStore StoreLoad
Implementation sketch A synchronized block can be realized as follows: public class X { 	private int a,i; 	public void synchronized f(){ LoadLoad; LoadStore; i= a; 			a =i; StoreLoad; StoreStore; } }
Thank you for your attention! Questions?

More Related Content

What's hot

Building flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on QuarkusBuilding flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on QuarkusIvelin Yanev
 
Browsing Linux Kernel Source
Browsing Linux Kernel SourceBrowsing Linux Kernel Source
Browsing Linux Kernel SourceMotaz Saad
 
An other world awaits you
An other world awaits youAn other world awaits you
An other world awaits you信之 岩永
 
BKK16-208 EAS
BKK16-208 EASBKK16-208 EAS
BKK16-208 EASLinaro
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
[En] IPVS for Docker Containers
[En] IPVS for Docker Containers[En] IPVS for Docker Containers
[En] IPVS for Docker ContainersAndrey Sibirev
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architectureElizabeth Smith
 
Java Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsJava Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsBrendan Gregg
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 
Futex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsFutex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsDavidlohr Bueso
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu WorksZhen Wei
 
LISA2019 Linux Systems Performance
LISA2019 Linux Systems PerformanceLISA2019 Linux Systems Performance
LISA2019 Linux Systems PerformanceBrendan Gregg
 
Using Kafka in your python application - Python fwdays 2020
Using Kafka in your python application - Python fwdays 2020Using Kafka in your python application - Python fwdays 2020
Using Kafka in your python application - Python fwdays 2020Oleksandr Tarasenko
 
Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBshimosawa
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkMohit Kanwar
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Effective service and resource management with systemd
Effective service and resource management with systemdEffective service and resource management with systemd
Effective service and resource management with systemdDavid Timothy Strauss
 

What's hot (20)

Building flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on QuarkusBuilding flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on Quarkus
 
Browsing Linux Kernel Source
Browsing Linux Kernel SourceBrowsing Linux Kernel Source
Browsing Linux Kernel Source
 
An other world awaits you
An other world awaits youAn other world awaits you
An other world awaits you
 
BKK16-208 EAS
BKK16-208 EASBKK16-208 EAS
BKK16-208 EAS
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
[En] IPVS for Docker Containers
[En] IPVS for Docker Containers[En] IPVS for Docker Containers
[En] IPVS for Docker Containers
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Java Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsJava Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame Graphs
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
Linux Internals - Part II
Linux Internals - Part IILinux Internals - Part II
Linux Internals - Part II
 
Futex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsFutex Scaling for Multi-core Systems
Futex Scaling for Multi-core Systems
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 
Scanner class java
Scanner class javaScanner class java
Scanner class java
 
LISA2019 Linux Systems Performance
LISA2019 Linux Systems PerformanceLISA2019 Linux Systems Performance
LISA2019 Linux Systems Performance
 
Using Kafka in your python application - Python fwdays 2020
Using Kafka in your python application - Python fwdays 2020Using Kafka in your python application - Python fwdays 2020
Using Kafka in your python application - Python fwdays 2020
 
Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKB
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Effective service and resource management with systemd
Effective service and resource management with systemdEffective service and resource management with systemd
Effective service and resource management with systemd
 

Viewers also liked

Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8AppDynamics
 
Java 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesJava 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesHaim Yadid
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Java memory presentation
Java memory presentationJava memory presentation
Java memory presentationYury Bubnov
 
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJ
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJIntroduktion till Aspekt-orienterad programmering (AOP) med AspectJ
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJMattias Jiderhamn
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingHaim Yadid
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
Java GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuningekino
 
Java gc
Java gcJava gc
Java gcNiit
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyDhanu Gupta
 
Вячеслав Блинов «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
 

Viewers also liked (20)

Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8
 
Java GC, Off-heap workshop
Java GC, Off-heap workshopJava GC, Off-heap workshop
Java GC, Off-heap workshop
 
Java memory model
Java memory modelJava memory model
Java memory model
 
Java 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesJava 8 Launch - MetaSpaces
Java 8 Launch - MetaSpaces
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
ClassLoader Leaks
ClassLoader LeaksClassLoader Leaks
ClassLoader Leaks
 
Java memory presentation
Java memory presentationJava memory presentation
Java memory presentation
 
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJ
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJIntroduktion till Aspekt-orienterad programmering (AOP) med AspectJ
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJ
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profiling
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
[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 GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuning
 
Java gc
Java gcJava gc
Java gc
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- Study
 
Вячеслав Блинов «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 Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 

Similar to The Java Memory Model

Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
jvm/java - towards lock-free concurrency
jvm/java - towards lock-free concurrencyjvm/java - towards lock-free concurrency
jvm/java - towards lock-free concurrencyArvind Kalyan
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On ConcurrencyWill Gage
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performanceRoger Xia
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On ConcurrencyRodney Barlow
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrencyaviade
 
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Gaetano Giunta
 
CrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataCrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataRaphael do Vale
 
Concurrency Utilities Overview
Concurrency Utilities OverviewConcurrency Utilities Overview
Concurrency Utilities Overviewwhite paper
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Architecture of the oasis mobile shared virtual memory system
Architecture of the oasis mobile shared virtual memory systemArchitecture of the oasis mobile shared virtual memory system
Architecture of the oasis mobile shared virtual memory systemZongYing Lyu
 

Similar to The Java Memory Model (20)

Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
jvm/java - towards lock-free concurrency
jvm/java - towards lock-free concurrencyjvm/java - towards lock-free concurrency
jvm/java - towards lock-free concurrency
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On Concurrency
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On Concurrency
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
 
CrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataCrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked data
 
Concurrency Utilities Overview
Concurrency Utilities OverviewConcurrency Utilities Overview
Concurrency Utilities Overview
 
G pars
G parsG pars
G pars
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Architecture of the oasis mobile shared virtual memory system
Architecture of the oasis mobile shared virtual memory systemArchitecture of the oasis mobile shared virtual memory system
Architecture of the oasis mobile shared virtual memory system
 
Multithreading
MultithreadingMultithreading
Multithreading
 

Recently uploaded

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

The Java Memory Model

  • 1. The Java Memory Model Alexander Martens
  • 2. Structure What is a memory model about? Platform memory models Annotation: Formal semantics Pro & Contra The new Java Memory Model (JMM) History Atomicity rules Ordering rules Visibility rules Piggybacking on synchronization Publication Initialization safety Changes Implementation sketch
  • 3. What is a memory model about? A memory model defines the behavior of threads how to interact through shared mutual memory. Therefore you need rules for Atomicity: Which operations are atomic? Ordering: In which order do the operations happen? Visibility: When is the modified data visible to other processors? These depends on the memory model at processor level, because of the varying degrees of cache coherence across different architectures.
  • 5. Platform memory models defines what guarantees programs can expect from the memory Atomicity: Which operations are not interrupted by the scheduler? Ordering: In which situation are operations reordered to achieve maximum performance? Visibility: Which writes to shared mutual memory are visible to other processors at any given time? specifies memory barriers (special instructions of a processor) to enforce an ordering constraint Some processors exhibit a strong memory model, other processors exhibit a weaker memory model (different processors are able to see different values for the same memory location).
  • 6. JMM and PMM JMM can be seen as an abstraction layer across different multiprocessor architectures. In dependence to the underlying hardware, the Java compiler deals with the differences by inserting memory barriers at the appropriate places to maintain the rules of the JMM.
  • 7. Annotation: Formal semantics Together with the definition of single-threaded execution, the memory model specifies the formal semantics of a programming language. Typically, in a single-threaded environment the compiler is required to implement as-if-serial semantics. As-if-serial: All actions of a thread can be reordered for optimization, as long as the result is the same as if they are ordered in program order.
  • 8. Pro & Contra Pro A programmer can reason about code execution. Atomicity and visibility is well-regulated. A data race can be prevented, because of ordering rules. A data race occurs, if a reads and writes of different threads on the same variable are not in a partial order. A compiler / processor is able to perform important optimizations, like loop fusion, in multi-threaded environment to achieve maximum performance. Contra The memory model also leads to performance cost, because of locks and other communication stuff.
  • 9. History 1991: Oak was developed under the name "The Green Project" by James Goslip and other developers within 18 months. The project was initiated by Sun Microsystems to develop a kernel for executing safe, portable, object-oriented and multi-threaded software on set-top boxes. 1995: Java 1.0 has been published by Sun Microsystems.
  • 10. History 2004: The original memory model was updated through the Java Community Process, as Java Specification Request 133, for Java 5.0, because the old one prevented many runtime optimizations and it didn’t provide enough guarantees for code safety.
  • 11. Atomicity rules Accesses to variables of primitive types (excluding long and double) and reference variables are atomic. Accesses to volatile variables of primitive types (including long and double) and reference variables are atomic. Operations on atomic variables in the package „java.util.concurrent.atomic“ are atomic, too.
  • 12. Ordering rules JMM defines an happens-before partially order for all instructions in a multi-threaded program. The order guarantees: Thread B will see the result of Thread A, if there exists a happens-before relation between B and A (because of corresponding visibility rules). If there exists a happens-before relation, the order of instructions will be reordered at will.
  • 13. Happens-before order Program order rule Monitor lock rule Volatile variable rule Thread start rule Thread termination rule Interruption rule Finalizer rule Transitivity
  • 14. Visibility rules Thread rule Monitor lock rule Volatile variable rule Atomic variable rule Final variable rule
  • 15. Piggybacking on synchronization Piggybacking on synchronization means combining the program order rule with the monitor lock rule or volatile variable rule concerning ordering and visibility of ordering and visibility, appearing in a code sequence. Pro: Not every method must be synchronized. Performance benefit A global order can be asserted by using a volatile variable as a guard.
  • 16. Publication The absence of a happens-before order between publishing a shared object and accessing it leads to a partially constructed object. @NotThreadSafe public class UnsafeLazyInitialization{ private static Resource resource; public static Resource getInstance() { if (resource == null) resource = new Resource(); return resource; } }
  • 17. Thread-safe lazy initilization Thread-safe lazy initialization is guaranteed by synchronization of the getInstance method. @ThreadSafe public class SafeLazyInitialization{ private static Resource resource; public synchronized static Resource getInstance() { if (resource == null) resource = new Resource(); return resource; } }
  • 18. Double-checked locking Antipattern (not thread safe), invented to reduce the impact of synchronization. In the original JMM synchronization was expensive concerning performance. Since JRE 5.0 it’s obsolete, because of a tuned JVM (especially JMM). Now it’s better to use thelazy initialization holder class idiom to gain performance, because it offers the same benefit and is easier to understand.
  • 19. Double-checked locking @NotThreadSafe public class DoubleCheckedLocking{ private static Resource resource; public static Resource getInstance() { if (resource == null) { synchronized (doubleCheckedLocking.class) { if (resource == null) resource = new Resource(); } } } }
  • 20. Lazy initialization holder class idiom combines the safe lazy initialization with the lazy initialization holder class idiom does not require synchronization, because of eager class initialization idiom @ThreadSafe public class ResourceFactory{ private static class ResourceHolder{ public static Resource resource= new Resource(); } public static Resource getResource() { return ResourceHolder.resource; } }
  • 21. Initialization safety Allows properly constructed immutable objects to be safely shared across threads without synchronization. Threads, obtaining a reference to that objects, are guaranteed to see up-to-date values of final fields. Initial writes aren’t reordered with accesses, coming after the final field is frozen.
  • 22. Changes Accesses to volatile variables won’t be reordered with any other memory operation. useful for using a volatile variable as a guard static int a = 0, b = 0; static int x = 0, y = 0; static volatile boolean initialized =false;   //Thread A a = 1; b = 1; initialized =true;   //ThreadB while(!initialized){} x = a; y = b;
  • 23. Changes Introduction of the happens-before order The initialization of final fields will never be reordered with operations following the finalization associated with the end of the constructor. Final means final.
  • 24. Implementation sketch Dependent on the underlying hardware platform model , the Java compiler insert the right memory barriers/fences, so that the Java memory model is valid. In a general model, the following fences exist: LoadLoad StoreStore LoadStore StoreLoad
  • 25. Implementation sketch A synchronized block can be realized as follows: public class X { private int a,i; public void synchronized f(){ LoadLoad; LoadStore; i= a; a =i; StoreLoad; StoreStore; } }
  • 26. Thank you for your attention! Questions?