The Java Memory Model

Similar documents
Advanced concurrent programming in Java Shared objects

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

The Java Memory Model

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Threads and Java Memory Model

Concurrency WS 2010/2011 The Java Memory Model

The New Java Technology Memory Model

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Lecture 17: Sharing Objects in Java

Sharing Objects Ch. 3

Lecture 32: Volatile variables, Java memory model

Threads and Locks. Chapter Introduction Locks

What is a thread anyway?

Audience. Revising the Java Thread/Memory Model. Java Thread Specification. Revising the Thread Spec. Proposed Changes. When s the JSR?

G52CON: Concepts of Concurrency

Sharing Objects. Java and Android Concurrency.

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Get out, you will, of this bind If, your objects, you have confined

Threads Questions Important Questions

JSR-133: Java TM Memory Model and Thread Specification

Advanced MEIC. (Lesson #18)

CMSC 132: Object-Oriented Programming II. Threads in Java

Synchronization in Java

CS 159: Parallel Processing

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

G52CON: Concepts of Concurrency

Principles of Software Construction: Concurrency, Part 2

Synchronization SPL/2010 SPL/20 1

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

CST242 Concurrency Page 1

MultiJav: A Distributed Shared Memory System Based on Multiple Java Virtual Machines. MultiJav: Introduction

Java Platform Concurrency Gotchas

Java Memory Model for practitioners. by Vadym Kazulkin and Rodion Alukhanov, ip.labs GmbH

Synchronization

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

A unified machine-checked model for multithreaded Java

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

CMSC 433 Spring 2013 Exam 1

Review of last lecture. Goals of this lecture. DPHPC Overview. Lock-based queue. Lock-based queue

CMSC 330: Organization of Programming Languages

Contents. 6-1 Copyright (c) N. Afshartous

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

Unit Testing in Java with an Emphasis on Concurrency Corky Cartwright Rice and Halmstad Universities Summer 2013

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

User Space Multithreading. Computer Science, University of Warwick

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Programming in Parallel COMP755

Advanced Java Multithreading Techniques

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

System Programming. Practical Session 4: Threads and Concurrency / Safety

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

Introduction to Locks. Intrinsic Locks

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Java Memory Model. Jian Cao. Department of Electrical and Computer Engineering Rice University. Sep 22, 2016

Kotlin/Native concurrency model. nikolay

Java s Implementation of Concurrency, and how to use it in our applications.

Multi-threaded programming in Java

Race Conditions & Synchronization

CPSC/ECE 3220 Fall 2017 Exam Give the definition (note: not the roles) for an operating system as stated in the textbook. (2 pts.

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency

Shared Memory Programming with OpenMP. Lecture 8: Memory model, flush and atomics

Safety SPL/2010 SPL/20 1

Review of last lecture. Peer Quiz. DPHPC Overview. Goals of this lecture. Lock-based queue

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Synchronization COMPSCI 386

RCU in the Linux Kernel: One Decade Later

Synchronising Threads

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

C++ Memory Model. Don t believe everything you read (from shared memory)

Atomicity via Source-to-Source Translation

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

Virtual Machine Design

CS342: Software Design. November 21, 2017

CSE 374 Programming Concepts & Tools

CSE 451 Midterm 1. Name:

Using Weakly Ordered C++ Atomics Correctly. Hans-J. Boehm

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Java Threads and intrinsic locks

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Multi-threading in Java. Jeff HUANG

Foundations of the C++ Concurrency Memory Model

Race Conditions & Synchronization

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Computing Approximate Happens-Before Order with Static and Dynamic Analysis

Chapter 2 Processes and Threads

Problems with Concurrency. February 19, 2014

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

Exercise Session Week 8

Introduction to Java Threads

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Atomicity for Reliable Concurrent Software. Race Conditions. Motivations for Atomicity. Race Conditions. Race Conditions. 1. Beyond Race Conditions

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Transcription:

The Java Memory Model What is it and why would I want one? Jörg Domaschka. ART Group, Institute for Distributed Systems Ulm University, Germany December 14, 2009

public class WhatDoIPrint{ static int x = 0, y = 0, a = 0, b = 0; public static void main(string[] args){ Thread one = new Thread(new Runnable(){ public void run(){ a = 1; x = b; } )}; Thread other = new Thread(new Runnable(){ public void run(){ b = 1; y = a; } )}; } one.start(); other.start(); one.join(); other.join(); System.out.println( ( + x +, + y + ) );

Possible Results Obviously: (1,0), (1,1), (0,1) Surprisingly: (0,0) Why that? Code reordering x = b (0) reorder a = 1 b = 1 y = a (0)

Reorderings Every entity optimises heavily Compiler Processor Caches In our case No shared variables declared Optimise for local operation

Outline Motivation JMM in a Nutshell The final Keyword Conclusions

Definitions Memory Model: Specifies when actions of one thread on memory are guaranteed to be visible by others. Defines: What you can expect from the system Operations for additional support Used in Multi-core/cpu architecture Multi-level caching

Java Memory Model Minimal guarantees the JVM must make about when writes to variables become visible. predictability and ease of programming vs high-performance What can we expect? Which additional operations do we have?

What to Expect? Sequential Consistency Mental model of many programmers A happy, if unrealistic model [Goetz] The von Neumann model is only a vague approximation [Goetz]

What to Expect? In the absence of special operations: Java provides barely any inter-thread guarantees Execution of a single thread is as-if sequential Don t expect anything Unless you prepared for it

Special Operations? In JMM Threads execute actions Actions are partially ordered (happens-before: antisymmetric, reflexive, transitive) Default: actions of different threads are not ordered

Special Actions! Inter-thread ordering actions Lock/unlock on monitor Volatile variables Thread start/termination/interruption... Synchronize all caches with main memory (Piggybacking on synchronization is possible) Define a synchronizes-with relation

Synchronisation Actions Totally ordered With respect to a single mutex/volatile variable No ordering guarantees for distinct variables Synchronized programmes Data race: Conflicting access to a shared variable that is not synchronized Correctly synchronized: All sequentially consistent executions are free of data races

Correct or Not? Thread 1: Thread 2: X = 1; Lock M1; Y = 1; Unlock M1; Lock M1; i = Y; Unlock M1; j = X;

Correct or Not? Thread 1: X = 1 Thread 2: Lock M1 Lock M1 i = Y Y = 1 Unlock M1 Unlock M1 j = X

Correct or Not? Thread 1: X = 1 Thread 2: Lock M1 Lock M1 i = Y Y = 1 Unlock M1 Unlock M1 j = X

Best Practices - Locking Every shared, mutable variable Guarded by exactly one lock Invariants that involve multiple variables All variables must be guarded by the same lock Resist the temptation to prematurely sacrifice simplicity for the sake of performance.

Best Pratices - volatile Volatile variables can only guarantee visibility. Writes must not depend on current value Does not participate in invariants Locking is not required for other reasons

Outline Motivation JMM in a Nutshell The final Keyword Conclusions

The final Keyword Semantics of final Fields Initialised once Never changed under normal circumstances Allows for compiler optimisations Do not depend on memory barriers (i.e., locks) Can always be cached Benefit: thread-safe immutable objects

final s Effect on Memory Freezing final fields At end of constructor But not before Reading a final field by constructing thread before freeze yields default value Allows building immutable objects Vital to Java security architecture Strings must not change

final s Visibility Guarantees After freeze of Object o All threads see correct value of final fields and fields exclusively reachable through them if they obtained reference to o after the freeze Non-final fields Only guaranteed to bee seen correctly by finalizer Unless synchronisation is used Requires safe publication of objects

Example class FinalFieldExample { final int x; int y; static FinalFieldExample f; public FinalFieldExample(){ x = 3; y = 4; } } static void reader(){ if (f!= null){ int i = f.x; int j = f.y; } } static void writer(){ f = new FinalFieldExample(); }

Example - Publication class UnsafeLazyInitialisation{ private static Resource resouce; } public static Resource getinstance(){ if(resource == null) resource = new Resource(); return resource; }

Example Publication (II) class SafeLazyInitialisation{ private static Resource resouce; } public synchronized static Resource getinstance(){ if(resource == null) resource = new Resource(); return resource; }

Example Publication (III) class EagerInitialisation{ private static Resource resouce = new Resource(); } public synchronized static Resource getinstance(){ return resource; }

Example Publication (IV) class ResourceFactory{ private static class ResourceHolder { public static Resource resource = new Resource(); } public synchronized static Resource getinstance(){ return ResourceHolder.resource; } }

Example Publication (V) pulic Holder holder; public void initialise(){ holder = new Holder(42); } public class Holder { private int n; public Holder(int i) { n = i; } } public void assertsanity(){ assert n == n : This statement is false ; }

Best Practices Sharing Objects Consider local variables/object No concurrency possible Consider using ThreadLocal One value per thread Use immutable objects where possible Immutable objects are always thread-safe If published correctly Make use of final Effect on visibility Easier reasoning about correctness

Best Practices - Publication Do not allow this references to escape during construction Consider using factory methods Do not start a thread from a constructor Use inheritance judiciously Publish safely

Best Practices Safe Publication Publish object reference and object state at the same time Static initialiser Write to volatile field or AtomicReference Store reference into a final field Store reference to a field guarded by a lock Placing an object in a unsynchronized Collection does not work in general

Outline Motivation Definitions JMM in a Nutshell The final Keyword Conclusions

Beyond Synchronisation JMM also defines Which reads/writes have to be atomic Semantics of wait and notify operations Parallel to interrupts Neither interrupt nor notify must get lost Semantics of sleep and yield Do not have any synchronisation semantics Semantics of modifying final fields

Conclusions JMM specifies when actions of one thread are guaranteed to be visible to another Threads run isolated: no guarantees Synchronisation actions provide inter-thread dependencies

Conclusions (II) final fields provide stronger guarantees (freeze when constructor finishes) Publish safely Locking can guarantee both: visibility and atomicity; volatile variables can only guarantee visibility.

References Goetz, Brian: Java Concurrency in Practice Bloch, Joshua: Effective Java Angelika Langer: Overview of the Java Memory Model Gosling, James et al.: The Java Language Specification, 3rd edition.

Modifying final fields Modification possible Using reflection Triggers an immediate freeze Sometimes required Executors, std{in,out,err} handlers Yet, discuraged Require additional compiler knowledge Counter-intuitive

Outline Motivation Definitions JMM in a Nutshell The final Keyword Best Practices Diving in Conclusions

Best Pratices Locking is not just about mutual exclusion; it is also about memory visibility. To ensure that all thread see the most up-to-date values of shared mutable variables, the reading and writing threads must synchronise on the same lock. Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.

Diving In