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



Similar documents
Chapter 6 Concurrent Programming

Outline of this lecture G52CON: Concepts of Concurrency

Mutual Exclusion using Monitors

Thread Synchronization and the Java Monitor

Monitors, Java, Threads and Processes

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

Lecture 6: Semaphores and Monitors

Real Time Programming: Concepts

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

Hoare-Style Monitors for Java

Last Class: Semaphores

Concurrent programming in Java

Java Memory Model: Content

Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

Shared Address Space Computing: Programming

Parallel Programming

Semaphores and Monitors: High-level Synchronization Constructs

KWIC Implemented with Pipe Filter Architectural Style

Ensuring Code Quality in Multi-threaded Applications

Atomicity for Concurrent Programs Outsourcing Report. By Khilan Gudka Supervisor: Susan Eisenbach

CS11 Java. Fall Lecture 7

Transactions and Recovery. Database Systems Lecture 15 Natasha Alechina

First-class User Level Threads

Java Virtual Machine Locks

Java Coding Practices for Improved Application Performance

CSC 2405: Computer Systems II

Design Patterns in C++

Synchronization in. Distributed Systems. Cooperation and Coordination in. Distributed Systems. Kinds of Synchronization.

TESTING JAVA MONITORS BY STATE SPACE EXPLORATION MONICA HERNANDEZ. Presented to the Faculty of the Graduate School of

Chapter 11 I/O Management and Disk Scheduling

Operating System: Scheduling

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

How To Write A Multi Threaded Software On A Single Core (Or Multi Threaded) System

Concurrent Programming

Facing the Challenges for Real-Time Software Development on Multi-Cores

Monitors and Semaphores

Processes and Non-Preemptive Scheduling. Otto J. Anshus

Lecture 6: Introduction to Monitors and Semaphores

Threads Scheduling on Linux Operating Systems

Chapter 2: OS Overview

Distributed Systems [Fall 2012]

3C03 Concurrency: Condition Synchronisation

Intel TSX (Transactional Synchronization Extensions) Mike Dai Wang and Mihai Burcea

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Glossary of Object Oriented Terms

Replication on Virtual Machines

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

SYSTEM ecos Embedded Configurable Operating System

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

In This Lecture. More Concurrency. Deadlocks. Precedence/Wait-For Graphs. Example. Example

Introduction to Embedded Systems. Software Update Problem

Deadlock Victim. dimanche 6 mai 12

Simple Cooperative Scheduler for Arduino ARM & AVR. Aka «SCoop»

Process Scheduling CS 241. February 24, Copyright University of Illinois CS 241 Staff

Chapter 11 I/O Management and Disk Scheduling

University of Dayton Department of Computer Science Undergraduate Programs Assessment Plan DRAFT September 14, 2011

Squashing the Bugs: Tools for Building Better Software

Testing and Inspecting to Ensure High Quality

MonitorExplorer: A State Exploration-Based Approach to Testing Java Monitors

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Outline. Review. Inter process communication Signals Fork Pipes FIFO. Spotlights

CS414 SP 2007 Assignment 1

ELEC 377. Operating Systems. Week 1 Class 3

Timing of a Disk I/O Transfer

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Parallel Computing. Shared memory parallel programming with OpenMP

Parallel Computing in Python: multiprocessing. Konrad HINSEN Centre de Biophysique Moléculaire (Orléans) and Synchrotron Soleil (St Aubin)

Moving from CS 61A Scheme to CS 61B Java

Android Application Development Course Program

Course Development of Programming for General-Purpose Multicore Processors

Control 2004, University of Bath, UK, September 2004

CS Fall 2008 Homework 2 Solution Due September 23, 11:59PM

Chapter 6, The Operating System Machine Level

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

Comp 204: Computer Systems and Their Implementation. Lecture 12: Scheduling Algorithms cont d

sqlite driver manual

Lecture Data Types and Types of a Language

RT Language Classes. Real-Time Programming Languages (ADA and Esterel as Examples) Implementation. Synchroneous Systems Synchronous Languages

A Survey of Parallel Processing in Linux

Spring 2011 Prof. Hyesoon Kim

COSC 6374 Parallel Computation. Parallel I/O (I) I/O basics. Concept of a clusters

Compute Cluster Server Lab 3: Debugging the parallel MPI programs in Microsoft Visual Studio 2005

Technical Properties. Mobile Operating Systems. Overview Concepts of Mobile. Functions Processes. Lecture 11. Memory Management.

Chapter 13 Storage classes

Threads 1. When writing games you need to do more than one thing at once.

3 - Lift with Monitors

Chapter 13 Embedded Operating Systems

Linux Driver Devices. Why, When, Which, How?

Between Mutual Trust and Mutual Distrust: Practical Fine-grained Privilege Separation in Multithreaded Applications

Transcription:

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC

Outline Outline of Topics Review what we learned Synchronising Threads

thread process emory segments Other Data resources Multithreaded process Code Data Other resources Stack Register Register Register Stack Stack Stack

Problems will arise when multiple threads access the shared resources: Q: How threads communicate/coordinate? A: Essentially by sharing the same memory space, e.g., access to fields and the objects reference fields refer to. Efficient, but makes two kinds of errors possible: Thread interference Memory consistency errors Note: Critical section - a piece of code that accesses a shared resource

Thread interference Also called race conditions Errors are introduced when multiple threads access and try to change the same resource, e.g., memory (variables, arrays, objects), system (databases) or file Let s take a look a very simple example: adding/subtracting some values from 0. We first define a Class Counter to do adding/subtracting Suppose we want to reference a Counter object from two threads which add 1 and then subtract 1. We expect we should get the outputs of 0 from both threads, but sometimes it is not. Why?

Atomic operations Atomic operation: an action either happens completely, or it doesn t happen at all. Even for a simple add() method, there are three atomic operations: Step 1: Load value from counter into a register Step 2: Add some value to the register Step 3: Store the value in the register back to counter

Thread interference Simple example: two threads try to increase an integer value by 1 (and later both decrease the vaule by 1) The steps when it went wrong: Thread 1 Thread 2 Integer value 0 read value to r1 0 read value to r2 0 increase value in r1 0 increase value in r2 0 write back 1 write back 1 Step 1: Load integer value to a register Step 3: Store the register to integer vaule

Thread interference: danger and solution Please read and execute my code example for thread interference. You might notice most of the time it runs perfectly well This kind of bug is particularly difficult to find and fix One solution: Synchronisation, that is enforcing exclusive access to a shared resource.

Memory consistency errors Memory consistency errors: different threads have inconsistent views of the same data. Example: Suppose we have one int field: int count = 0; counter is shared between two threads A and B Thread A increments counter: Thread B simply prints out counter: System.out.println(counter); The output might not be predictable. count++; No guarantee that thread A s change to counter will be visible to thread B

Memory consistency errors Memory consistency errors VS. thread interference Thread interference: happens when different threads are changing the same data Memory consistency errors: happens when different threads have different views of the same shared data. The causes of these errors are complex: we only need to know how to avoid them Key for avoiding these errors: understanding the happens-before relationship, also denoted as a b: event a should happen before event b, the result must reflect that no matter what order those events are in reality executed. A guarantee that memory written to by statement A is visible to statement B, that is, that statement A completes its write before statement B starts its read.

Ways of creating happens-before relationships for thrads For threads share the same data, we need to write code to explicitly implement happens-before relationships, esp. for executing new threads In Java, we can use Thread.join() Please take a look at my Java example Synchronisation

Synchronising Threads Synchronisation in Java Three tools for Synchronization: Locks: the most common synchronization tool Volatile Variables: establishes a happens-before relationship to solve the memory consistency errors Atomic Operations: nonblocking synchronization, ensure an action either happens completely, or it doesn t happen at all to solve the thread interference problem Two ways of using locks: Reentrant Locks, and Synchronized keyword Two ways of using Synchronized keyword in Java: Synchronized methods, and Synchronized statements/blocks Differences: simply put, synchronized methods are simpler but less flexible Please see two Java examples

Synchronising Threads Mechanisms behind Java synchronisation: Intrinsic lock Synchronization is built around an internal entity known as the intrinsic lock, or monitor lock, or simple lock. In Java, every object has an intrinsic lock associated with it Intrinsic lock does two things: enforcing exclusive access to an object s state; and establishing happens-before relationships How it works: Thread A acquires the object s intrinsic lock before accessing the object s field exclusive access No other thread can acquire the same lock before Thread A releases the lock happens-before relationships accessing It release the intrinsic lock when finishes

Synchronising Threads Mechanisms behind Java synchronisation: monitor An important concept in concurrent programming and operating system Monitor: a synchronization mechanism that allows threads: to have mutual exclusion to have the ability to wait for a certain condition to become true to signal other threads that their condition has been met. A monitor can be formally defined as M = (m, c), where m is intrinsic lock object and c a condition variable. Intrinsic lock m: ensures exclusive access and happens-before relationships Condition c: ensures threads attempting an operation to wait until some condition, e.g., job queue is not empty, is met A monitor is basically a container of threads that are waiting on a certain condition.

Synchronising Threads Mechanisms behind Java synchronisation: monitor Meeting room (monitor region) Bank (Monitor) Step 3: Release Some object with intrinsic lock Waiting room (waiting set) Step 5: release and exit Step 4: Acquire Step 2: If not occupied, occupy monitor region If occupied, entre waiting set Hallway (Entry set) Some scheduling: FIFO An active thread A waiting thread Step 1: entre entry set