SlideShare ist ein Scribd-Unternehmen logo
1 von 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?

Weitere ähnliche Inhalte

Was ist angesagt?

JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 

Was ist angesagt? (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
 

Andere mochten auch

Java memory presentation
Java memory presentationJava memory presentation
Java memory presentation
Yury 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 AspectJ
Mattias Jiderhamn
 
Java gc
Java gcJava gc
Java gc
Niit
 

Andere mochten auch (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
 

Ähnlich wie The Java Memory Model

Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
aviade
 
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
 
Concurrency Utilities Overview
Concurrency Utilities OverviewConcurrency Utilities Overview
Concurrency Utilities Overview
white paper
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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...
 
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
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

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?