Synchronization in Java

Similar documents
CMSC 132: Object-Oriented Programming II

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

The New Java Technology Memory Model

Multi-threading in Java. Jeff HUANG

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

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

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Problems with Concurrency. February 19, 2014

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

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

What is a thread anyway?

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Threads and Java Memory Model

Threads Chate Patanothai

Concurrent Programming Lecture 10

Introduction to Java Threads

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

Question Points Score Total 100

RACE CONDITIONS AND SYNCHRONIZATION

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

Synchronization in Concurrent Programming. Amit Gupta

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Programming Language Concepts: Lecture 11

Monitors; Software Transactional Memory

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

Lecture 29: Java s synchronized statement

CMSC 330: Organization of Programming Languages

Models of concurrency & synchronization algorithms

Monitors; Software Transactional Memory

CS 159: Parallel Processing

Advanced Concepts of Programming

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

Animation Part 2: MoveableShape interface & Multithreading

Threads and Parallelism in Java

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

COMP346 Winter Tutorial 4 Synchronization Semaphores

Threads, Concurrency, and Parallelism

CS11 Java. Fall Lecture 7

public class Shared0 { private static int x = 0, y = 0;

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

Question Points Score Total 100

Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)

Shared-Memory and Multithread Programming

CSE332: Data Abstractions Lecture 25: Deadlocks and Additional Concurrency Issues. Tyler Robison Summer 2010

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

Part IV Other Systems: I Java Threads

CS 556 Distributed Systems

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

User Space Multithreading. Computer Science, University of Warwick

OS06: Monitors in Java

Programming in Parallel COMP755

Java Threads. Introduction to Java Threads

Programmazione di sistemi multicore

Multiple Inheritance. Computer object can be viewed as

CS18000: Programming I

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

1 Multiple Threads of Control

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

Java Threads. Written by John Bell for CS 342, Spring 2018

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

Lecture 9: Introduction to Monitors

The Java Memory Model

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Reintroduction to Concurrency

Concurrent Programming using Threads

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

Concurrency in Java Prof. Stephen A. Edwards

Java Threads. COMP 585 Noteset #2 1

Parallel & Concurrent Programming

CSE 153 Design of Operating Systems

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

Resource management. Real-Time Systems. Resource management. Resource management

CS193k, Stanford Handout #8. Threads 3

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

Introduction to Locks. Intrinsic Locks

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Concurrent Objects and Linearizability

Principles of Software Construction: Concurrency, Part 2

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Dealing with Issues for Interprocess Communication

G52CON: Concepts of Concurrency

Monitors CSCI 201 Principles of Software Development

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Synchronization I. Jo, Heeseung

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam.

Programming Languages

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Transcription:

Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park

Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait / Notify

Unsufficient atomicity Very frequently, you will want a sequence of actions to be performed atomically or indivisibly not interrupted or disturbed by actions by any other thread x++ isn t an atomic operation it is a read followed by a write Can be a intermittent error depends on exact interleaving

Insuffient Atomicity Example public class InsuffientAtomicity implements Runnable { static int x = 0; public void run() { int tmp = x; x = tmp+1; public static void main(string[] args) { for (int i = 0; i < 3; i++) new Thread(new InsuffientAtomicity ()).start(); System.out.println(x); // may not be 3

Definition Data Race Concurrent accesses to same shared variable, where at least one access is a write variable isn t volatile Can expose all sorts of really weird stuff the compiler and processor are doing to improve performance

Quiz Time Thread 1 x = y = 0 start threads Thread 2 x = 1 y = 1 j = y i = x Can this result in i = 0 and j = 0?

Answer: Yes! Thread 1 x = y = 0 start threads Thread 2 x = 1 y = 1 j = y i = x How can i = 0 and j = 0?

How Can This Happen? Compiler can reorder statements Or keep values in registers Processor can reorder them On multi-processor, values not synchronized to global memory The memory model is designed to allow aggressive optimization including optimizations no one has implemented yet Good for performance bad for your intuition about insufficiently synchronized code

Uses Synchronization Marks when a block of code must not be interleaved with code executed by another thread Marks when information can/must flow between threads Notes Incurs a small amount of runtime overhead if only used where you might need to communicate between threads, not significant used everywhere, can add up

Definition Lock Entity can be held by only one thread at a time Properties A type of synchronization Used to enforce mutual exclusion Thread can acquire / release locks Thread will wait to acquire lock (stop execution) If lock held by another thread

Synchronized Objects in Java All Java objects provide locks Apply synchronized keyword to object Mutual exclusion for code in synchronization block block Example Object x = new Object(); void foo() { synchronized(x) { // acquire lock on x on entry... // hold lock on x in block // release lock on x on exit

Synchronized Methods In Java Java methods also provide locks Apply synchronized keyword to method Mutual exclusion for entire body of method Synchronizes on object invoking method Example block synchronized void foo() { code // shorthand notation for void foo() { synchronized (this) { code

Synchronized Methods In Java

Locks in Java Properties No other thread can get lock on x while in block Does not protect fields of x except by convention other threads can access/update fields but can t obtain lock on x By convention, lock x to obtain exclusive access to x Locked block of code critical section Lock is released when block terminates No matter how the block terminates: End of block reached Exit block due to return, continue, break Exception thrown

Using synchronization public class UseSynchronization implements Runnable { static int x = 0; static Object lock = new Object(); public void run() { synchronized(lock) { int tmp = x; x = tmp+1;

Questions What would happen if the lock field were not static? Why don t we just make the run method synchronized? Why don t we just synchronize on x?

Not sharing same lock public class NotSharingLock implements Runnable { static int x = 0; Object lock = new Object(); public void run() { synchronized(lock) { int tmp = x; x = tmp+1;

Synchronization Issues Use same lock to provide mutual exclusion Ensure atomic transactions Avoiding deadlock

Issue 1) Using Same Lock Potential problem Mutual exclusion depends on threads acquiring same lock No synchronization if threads have different locks Example void run() { Object o = new Object(); // different o per thread synchronized(o) { // potential data race

Locks in Java Single lock for all threads (mutual exclusion) Separate locks for each thread (no synchronization)

Issue 2) Atomic Transactions Potential problem Sequence of actions must be performed as single atomic transaction to avoid data race Ensure lock is held for duration of transaction Example synchronized(lock) { int tmp = x; // both statements must // be executed together x = tmp; // by single thread

Using synchronization public class InsuffientAtomicity implements Runnable { static int x = 0; static Object lock = new Object(); public void run() { int tmp; synchronized(lock) { tmp = x; ; synchronized(lock) { x = tmp+1;

Issue 3) Avoiding Deadlock In general, want to be careful about performing any operations that might take a long time while holding a lock What could take a really long time? getting another lock Particularly if you get deadlock

Deadlock Example 1 Thread1() { Thread2() { synchronized(a) { synchronized(b) { synchronized(b) { synchronized(a) { // Thread1 holds lock for a, waits for b // Thread2 holds lock for b, waits for a

Deadlock Example 2 void movemoney(account a, Account b, int amount) { synchronized(a) { synchronized(b) { a.debit(amount); b.credit(amount); Thread1() { movemoney(a,b,10); // holds lock for a, waits for b Thread2() { movemoney(b,a,100); // holds lock for b, waits for a

Waiting for Godot Sometimes, you need to wait for another thread else to do something before you can do something

Buffer Abstract Data Type Buffer Transfers items from producers to consumers Very useful in multithreaded programs Synchronization needed to prevent multiple consumers removing same item

Producer thread calls buffer.add(o) adds o to the buffer Buffer usage Consumer thread calls buffer.remove() if object in buffer, removes and returns it otherwise, waits until object is available to remove

Buffer Implementation public class Buffer { private LinkedList objects = new LinkedList(); public synchronized add( Object x ) { objects.add(x); public synchronized Object remove() { while (objects.isempty()) { ; // waits for more objects to be added return objects.removefirst(); // if empty buffer, remove() holds lock and waits // prevents add() from working deadlock

Eliminating Deadlock public class Buffer { private Object [] myobjects; private int numberobjects = 0; public synchronized add( Object x ) { objects.add(x); public Object remove() { while (true) { // waits for more objects to be added synchronize(this) { if (!objects.isempty()) { return objects.removefirst(); // if empty buffer, remove() gives // up lock for a moment

Might work Works barely, if at all But waiting thread is going to be running a full tilt, twiddling its thumbs, doing nothing burning up your battery life keeping the producer from getting the CPU time it needs to quickly produce a new object

Issue 4) Using Wait & Notify Potential problem Threads actively waiting consume resources Solution Can wait to be notified Use Thread class methods wait(), notifyall() notify() is for advanced use and tricky to get right; avoid it

Thread Class Wait & Notify Methods wait() Invoked on object must already hold lock on that object gives up lock on that object goes into a wait state notifyall() Invoked on object must already hold lock on that object all threads waiting on that object are woken up but they all gave up their lock when they performed wait will have to regain lock before then can run thread performing notify holds lock at the moment

State transitions Using Wait & Notify

Using Wait and NotifyAll public class Buffer { private LinkedList objects = new LinkedList(); public synchronized add( Object x ) { objects.add(x); this.notifyall(); public synchronized Object remove() { while (objects.isempty()) { this.wait(); return objects.removefirst();

Actually, that won t compile the wait() method is declared to throw an InterruptedException a checked exception You rarely have situations where a wait will throw an InterruptedException but the compiler forces you to deal with it

Using Wait and NotifyAll public class Buffer { private LinkedList objects = new LinkedList(); public synchronized add( Object x ) { objects.add(x); this.notifyall(); public synchronized Object remove() { while (objects.isempty()) { try { this.wait(); catch (InterruptedException e) { return objects.removefirst();