COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C.

Slides:



Advertisements
Similar presentations
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Chapter 6: Process Synchronization
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Week 9, Class 3: Model-View-Controller Final Project Worth 2 labs Happens-Before ( SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
COMPSCI 230 S2C 2013 Software Design and Construction Introduction to Java Threads Lecture 1 of Theme C.
Object-Oriented Software Engineering Concurrent Programming.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Definitions Process – An executing program
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
Threads some important concepts Simon Lynch
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
111 © 2002, Cisco Systems, Inc. All rights reserved.
COMPSCI 230 S2C 2015 Software Design and Construction Lecture 5 of Theme C Locking, blocking, mutex; visibility, consistency.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Internet Software Development Controlling Threads Paul J Krause.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
COMPSCI 230 S2C 2013 Software Design and Construction Deadlock, Performance, Programming Guidelines Lecture 6 of Theme C.
Synchronizing threads, thread pools, etc.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
Week 9, Class 3: Java’s Happens-Before Memory Model (Slides used and skipped in class) SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
Today Quiz not yet graded Final report requirements posted More on Multithreading Happens-Before in Java SE-2811 Slide design: Dr. Mark L. Hornick Content:
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Component-Based Software Engineering Understanding Thread Safety Paul Krause.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Synchronization Questions answered in this lecture: Why is synchronization necessary? What are race conditions, critical sections, and atomic operations?
pThread synchronization
Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.
Sun Proprietary/Confidential: Internal Use Only 1 Multi-Threading Primer Byron Nevins December 10, 2007.
Java Thread Programming
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Lecture 24 Concurrency 2 (D&D 23) Date.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreaded Programming in Java
Week 6, Class 2: Observer Pattern
Synchronization Lecture 23 – Fall 2017.
More on Thread Safety CSE451 Andrew Whitaker.
Multithreading.
Java Concurrency 17-Jan-19.
9. Threads SE2811 Software Component Design
Java Concurrency.
Multithreading in java.
Java Concurrency.
Threads and Multithreading
Java Concurrency 29-May-19.
Problems with Locks Andrew Whitaker CSE451.
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C

Learning Goals for Today  Develop a stronger understanding of synchronization in Java.  Be able to analyse codes with a small number of interactions between a few threads, answering the question “what execution traces are possible?”  Learn the syntax for synchronized methods  What are the disadvantages of this “syntactic sugar”?  Learn an important design pattern: using a final instance of a collection to synchronize its methods.  A simple example: a thread-safe cache C42

Goetz’s “Simple Synchronization Example”  “Using synchronized blocks allows you  to perform a group of related updates as a set  without worrying about other threads  interrupting or seeing the intermediate results of a computation. “  Do you understand why you should be concerned if  Other threads can interrupt a worker thread, or if  Other threads can see a worker’s intermediate results? C43

Atomicity, in detail  Atomic reading:  The variables read by a worker (in an atomic task) must be “locked” against changes by other threads -- until the worker has completed the task.  Atomic writing:  A worker’s writes must be invisible to other threads until the worker has finished their atomic task – and they must be visible to the next worker who enters this task.  Atomic completion:  While a worker is performing an atomic task, it should not be interrupted by other workers.  This is not an absolute prohibition.  If a thread is interrupted, it has to start over from the beginning of the task – and this slows progress.  In an extreme case (called livelock), every worker attempting the task is interrupted by another worker, so the task is never completed! C44

The top-level structure of Goetz’s example public class SyncExample { private static Object lockObject = new Object(); private static class Thread1 extends Thread { … // on next slide } private static class Thread2 extends Thread { … // on next slide } public static void main(String[] args) { new Thread1().start(); new Thread2().start(); } C45

Thread classes in Goetz’s example private static class Thread1 extends Thread { public void run() { synchronized( lockObject ) { x = y = 0; System.out.println(x); } } } private static class Thread2 extends Thread { public void run() { synchronized( lockObject ) { x = y = 1; System.out.println(y); } } } or Expected output: A thread cannot execute a synchronized block until it acquires the “lock” on the block’s monitor. The lock is released when the thread exits the block. A lock has at most one owner at any time. A thread can own many locks. C46

Unsynchronized threads private static class Thread1 extends Thread { public void run() { y = 0; x = y = 0; x = 0; System.out.println(x); } } private static class Thread2 extends Thread { public void run() { y = 1; x = y = 1; x = 1; System.out.println(y); } } or Expected output: or C47

Synchronized Methods  We can synchronize the body of a method using this as its lock: public class Point { public void setXY( int x, int y ) { synchronized (this) { this.x = x; this.y = y; } } }  This is a very common structure, so Java includes the “synchronized method” as syntactic sugar.  See  The following is equivalent, and is sweeter to read and write. public class Point { public synchronized void setXY( int x, int y ) { this.x = x; this.y = y; }  Warning: sugar is very unhealthy if you don’t “eat your vegetables” too! C48

public class SyncExample { public static class Thingie { private Date lastAccess; public synchronized void setLastAccess( Date date ) { this.lastAccess = date; } } public static class MyThread extends Thread { private Thingie thingie; public MyThread( Thingie thingie ) { this.thingie = thingie; } public void run() { thingie.setLastAccess( new Date() ); } } public static void main() { Thingie thingie1 = new Thingie(), thingie2 = new Thingie(); new MyThread(thingie1).start(); new MyThread(thingie2).start(); } Dangerous Sugar… setLastAccess() is a synchronized method, so each instance has its own lock. This method is unsafe, because the first worker thread can acquire the lock on thingie1 at the same time the second worker acquires a lock on thingie2. C49

Goetz’s Advice on Synchronization  “Because synchronization prevents multiple threads from executing a block at once,  it has performance implications, even on uniprocessor systems.  “It is a good practice to  use synchronization around the smallest possible block of code that needs to be protected.  “Access to local (stack-based) variables never need to be protected,  because they are only accessible from the owning thread.”  In other words:  if you’re concerned about performance, don’t use this syntactic sugar (unless the whole method really needs to be “sweet” ;-). C410

Most Java Classes are not Synchronized!  Java has nice support for threads, but you have to be very careful whenever multiple threads can access the same object.  Goetz: “Because synchronization carries a small performance penalty,  most general-purpose classes, like the Collection classes in java.util, do not use synchronization internally.  This means that classes like HashMap cannot be used from multiple threads without additional synchronization.  “You can use the Collections classes in a multithreaded application  by using synchronization every time you access a method in a shared collection.  For any given collection, you must synchronize on the same lock each time.  A common choice of lock would be the collection object itself.  “If the documentation for a class does not say that it is thread-safe, then you must assume that it is not.” C411

public class SimpleCache { private final Map cache = new HashMap(); public Object load(String objectName) { // load the object somehow } public void clearCache() { synchronized( cache ) { cache.clear(); } } public Object getObject( String objectName ) { synchronized( cache ) { Object o = cache.get( objectName ); if( o == null ) { o = load( objectName ); cache.put( objectName, o ); } } return o; } A Simple Thread-Safe Cache This code is synchronized on a single (final) instance of a cache object. The cache.clear() method will never run concurrently with a cache.get() or cache.put(). Cache updates are atomic: the cache.get()… cache.put() sequence won’t be interrupted. C412

Sharing access to data summary (Goetz)  “Because the timing of thread execution is nondeterministic, we need to be careful to control a thread’s access to shared data.  Otherwise, multiple concurrent threads could step on each other's changes and result in corrupted data, or  changes to shared data might not be made visible to other threads on a timely basis.  “By using synchronization to protect access to shared variables,  we can ensure that threads interact with program variables in predictable ways.  “Every Java object can act as a lock, and synchronized blocks can ensure that  only one thread executes synchronized code protected by a given lock at one time.” C413

Learning Goals for Today  Develop a stronger understanding of synchronization in Java.  Be able to analyse codes with a small number of interactions between a few threads, answering the question “what execution traces are possible?”  Learn the syntax for synchronized methods  What are the disadvantages of this “syntactic sugar”?  Learn an important design pattern: using a final instance of a collection to synchronize its methods.  A simple example: a thread-safe cache C414