Effective Java: Concurrency Last Updated: Spring 2010.

Slides:



Advertisements
Similar presentations
50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Advertisements

Concurrent Programming Abstraction & Java Threads
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Concurrency 101 Shared state. Part 1: General Concepts 2.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Effective Java: Concurrency Last Updated: Fall 2011.
©SoftMoore ConsultingSlide 1 Appendix D: Java Threads "The real payoff of concurrent execution arises not from the fact that applications can be speeded.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
Threading Part 4 CS221 – 4/27/09. The Final Date: 5/7 Time: 6pm Duration: 1hr 50mins Location: EPS 103 Bring: 1 sheet of paper, filled both sides with.
Threading Part 3 CS221 – 4/24/09. Teacher Survey Fill out the survey in next week’s lab You will be asked to assess: – The Course – The Teacher – The.
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.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Week 9 Building blocks.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Threads some important concepts Simon Lynch
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Effective Java: Generics Last Updated: Spring 2009.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
Java Thread and Memory Model
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Effective Java - Concurrency The scope of the topic Concurrency Distributed Parallel Multiply-Thread Multiply-Core Multiply-Box (Process/JVM)
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
Software and Threading Geza Kovacs Maslab Abstract Design: State Machines By using state machine diagrams, you can find flaws in your behavior without.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
CMSC 330: Organization of Programming Languages Threads.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Agenda  Quick Review  Finish Introduction  Java Threads.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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.
Java Thread Programming
Multithreading / Concurrency
Multithreading.
Background on the need for Synchronization
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Multithreaded Programming in Java
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Java Concurrency 17-Jan-19.
Java Concurrency.
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.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Threads and concurrency / Safety
Presentation transcript:

Effective Java: Concurrency Last Updated: Spring 2010

Concurrency in Java Agenda Material From Joshua Bloch Effective Java: Programming Language Guide Cover Items “Concurrency” Chapter Bottom Line: Primitive Java concurrency is complex

Concurrency in Java Some Background (from Java Concurrency in Practice, B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea) Thread: lightweight processes; execute simultaneously and asynchronously with each other; share same memory address space of owning process, all thread within a process have access to the same variables and allocate objects from the same heap Thread Safety Managing the state: with respect to shared and mutable state. Shared: accessed by multiple threads. Mutable: value could change during lifecycle.

Concurrency in Java Some Background (from Java Concurrency in Practice, B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea) Thread Safety???: Correctness – invariants; postconditions “A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of the threads by the runtime environment, and with no additoinal synchronization or other coordination on the part of the calling code.” “Thread-safe encapsulate any needed synchronization so that clients need not provide their own.”

Concurrency in Java Java Concurrency Problems: Examples Race conditions – threads try to update the same data structure at the same time Deadlock – two threads need variables A and B to perform a calculation; one thread locks A and the other thread locks B; Starvation – a thread is unable to obtain CPU time due a higher priority threads

Concurrency in Java Thread Interference class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.

Concurrency in Java Thread Interference (concluded) c++ can be decomposed into three steps Retrieve the current value of c Increment the retrieved value by 1 Store the incremented value back in c Suppose Thread A invokes increment at about the same time Thread B invokes decrement. If the initial value of c is 0, their interleaved actions might follow this sequence: Thread A: Retrieve c. Thread B: Retrieve c. Thread A: Increment retrieved value; result is 1. Thread B: Decrement retrieved value; result is -1. Thread A: Store result in c; c is now 1. Thread B: Store result in c; c is now -1. N.B., Thread A's result is lost, overwritten by Thread B. This particular interleaving is only one possibility. Under different circumstances it might be Thread B's result that gets lost, or there could be no error at all. Because they are unpredictable, thread interference bugs can be difficult to detect and fix.

Concurrency in Java Memory Consistency Errors - Java Memory Model (from Java Concurrency in Practice, B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea) Partial ordering on Java program actions (happens- before) Read/write Lock/unlock Start/join threads If action X happens-before Y, then X’s results are visible to Y. Within a thread the order is the program order. Between threads, if synchronized or volatile is not used, there are no visibility guarantees (i.e., there is no guarantee that thread A will see them in the order that thread be executes them).

Concurrency in Java Item 66: Synchronize Access to Shared Mutable Data Method synchronization yields atomic transitions: public synchronized boolean doStuff() {…} Fairly well understood… Method synchronization also ensures that other threads “see” earlier threads Not synchronizing on shared “atomic” data produces wildly counterintuitive results Not well understood

Concurrency in Java Java Synchronization Communication between Java Threads Java synchronization is implemented using monitors Each object in Java is associated with a monitor, which a thread can lock and unlock Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor.

Concurrency in Java Basic tools of Java Thread Synchronization Synchronized keyword – an unlock happens-before every subsequent lock on the same monitor Volatile keyword – a write to a volatile variable happens- before subsequent reads of that variable; compiler and runtime are notified that the variable should not be reordered with memory operations; variables are not cached in registers or in caches where they are hidden from other processors, so a read of volatile variable always returns the most recent write by any thread (from Java Concurrency in Practice, B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea) Static initialization – done by the class loader, so the JVM guarantees thread safety

Concurrency in Java Atomic Example (from Java Concurrency in Practice, B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Public class UnsafeCountingFactorizer implements Servlet { private long count; public long getCount() { return count; } public void service(ServletRequest req, ServletResponse resp) { BigInteger I = extractFromRequest(req); BigInteger[] factors = factor(i); ++count; encodeIntoResponse(resp, factors); Why is this unsafe? Atomic – execute as a single, indivisible operation.

Concurrency in Java Item 66: Unsafe Example // Broken! How long do you expect this program to run? public class StopThread { private static boolean stopRequested; public static void main (String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { // May run forever! Liveness failure int i=o; while (! stopRequested) i++; // See below }}); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; } // Hoisting transform: // while (!loopTest) {i++;}  if (!loopTest) while(true) {i++;} // Also note anonymous class

Concurrency in Java Item 66: Fixing the Example // As before, but with synchronized calls public class StopThread { private static boolean stopReq; public static synchronized void setStop() {stopReq = true;} public static synchronized void getStop() {return stopReq;} public static void main (String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { // Now “sees” main thread int i=o; while (! getStop() ) i++; }}); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); setStop(); } // Note that both setStop() and getStop() are synchronized

Concurrency in Java Item 66: A volatile Fix for the Example // A fix with volatile public class StopThread { // Pretty subtle stuff, using the volatile keyword private static volatile boolean stopRequested; public static void main (String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i=o; while (! stopRequested) i++; }}); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; }

Concurrency in Java Item 66: volatile Does Not Guarantee Mutual Exclusion // Broken! Requires Synchronization! private static volatile int nextSerialNumber = 0; public static int generateSerialNumber() { return nextSerialNumber++; } Problem is that the “++” operator is not atomic // Even better! (See Item 47) private static final AtomicLong nextSerial = new AtomicLong(); public static long generateSerialNumber() { return nextSerial.getAndIncrement(); }

Concurrency in Java Item 66: Advice on Sharing Data Between Threads Confine mutable data to a single Thread May modify, then share (no further changes) Called “Effectively Immutable” Allows for “Safe Publication” Mechanisms for safe publication In static field at class initialization volatile field final field field accessed with locking (ie synchronization) Store in concurrent collection (Item 69)

Concurrency in Java Item 67: Avoid Excessive Synchronization // Broken! Invokes alien method from sychronized block public interface SetOb { void added(ObservableSet set, E el);} public class ObservableSet extends ForwardingSet { // Bloch 16 public ObservableSet(Set set) { super(set); } private final List > obs = new ArrayList >(); public void addObserver (SetObs ob ) { synchronized (obs) { obs.add(ob); } } public boolean removeObserver (SetOb ob ) { synchronized (obs) { return obs.remove(ob); } } private void notifyElementAdded (E el) { synchronized(obs) {for (SetOb ob:obs) // Exceptions? ob.added(this, public boolean add(E el) { // from Set interface boolean added = super.add(el); if (added) notifyElementAdded (el); return added; }}

Concurrency in Java More Item 67: What’s the Problem? public static void main (String[] args) { ObservableSet set = new ObservableSet (new HashSet ); set.addObserver (new SetOb () { public void added (ObservableSet s, Integer e) { System.out.println(e); if (e.equals(23)) s.removeObserver(this); // Oops! CME // See Bloch for a variant that deadlocks instead of CME } }); for (int i=0; i < 100; i++) set.add(i); }

Concurrency in Java More Item 67: Turning the Alien Call into an Open Call // Alien method moved outside of synchronized block – open call private void notifyElementAdded(E el) { List > snapshot = null; synchronized (observers) { snapshot = new ArrayList >(obs); } for (SetObserver observer : snapshot) observer.added(this, el) // No more CME }} Open Calls increase concurrency and prevent failures Rule: Do as little work inside synch block as possible When designing a new class: Do NOT internally synchronize absent strong motivation Example: StringBuffer vs. StringBuilder

Concurrency in Java Item 67: Alternate Fix Using CopyOnWriteArray public interface SetOb { void added(ObservableSet set, E el);} public class ObservableSet extends ForwardingSet { // Bloch 16 public ObservableSet(Set set) { super(set); } private final List > obs = new CopyOnWriteArrayList >(); public void addObserver (SetObs ob ) { synchronized (obs) { obs.add(ob); } } public boolean removeObserver (SetOb ob ) { synchronized (obs) { return obs.remove(ob); } } private void notifyElementAdded (E el) { {for (SetOb ob:obs) // Iterate on copy – No Synch! ob.added(this, public boolean add(E el) { // from Set interface boolean added = super.add(el); if (added) notifyElementAdded (el); return added; }}

Concurrency in Java Item 68: Prefer Executors and Tasks to Threads Old key abstraction: Thread Unit of work and Mechanism for execution New key abstractions: Task (Unit of work) Runnable and Callable Mechanism for execution Executor Service Start tasks, wait on particular tasks, etc. See Bloch for references

Concurrency in Java Item 69: Prefer Concurrency Utilities to wait and notify wait() and notify() are complex Java concurrency facilities much better Legacy code still requires understanding low level primitives Three mechanisms Executor Framework (Item 68) Concurrent collections Internally synchronized versions of Collection classes Extensions for blocking, Example: BlockingQueue Synchronizers Objects that allow Threads to wait for one another

Concurrency in Java More Item 69: Timing Example // Simple framework for timing concurrent execution public static long time (Executor executor, int concurrency, final Runnable action) throws InterrruptedExecution { final CountDownLatch ready = new CountDownLatch(concurrency); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(concurrency); for (int i=0; i< concurrency; i++) { executor.execute (new Runnable() { public void run() { ready.countDown(); // Tell Timer we’re ready try { start.await(); action.run(); // Wait till peers are ready } catch (...){...} } finally { done.countDown(); }} // Tell Timer we’re done });} ready.await(); // Wait for all workers to be ready long startNanos = System.nanoTime(); start.countDown(); // And they’re off! done.await() // Wait for all workers to finish return System.nanoTime() – startNanos; }

Concurrency in Java Item 70: Document Thread Safety Levels of Thread safety Immutable: Instances of class appear constant Example: String Unconditionally thread-safe Instances of class are mutable, but is internally synchronized Example: ConcurrentHashMap Conditionally thread-safe Some methods require external synchronization Example: Collections.synchronized wrappers Not thread-safe Client responsible for synchronization Examples: Collection classes Thread hostile: Not to be emulated!

Concurrency in Java Item 71: Use Lazy Initialization Judiciously Under most circumstances, normal initialization is preferred // Normal initialization of an instance field private final FieldType field = computeFieldValue(); // Lazy initialization of instance field – synchronized accessor private FieldType field; synchronized FieldType getField() { if (field == null) field = computeFieldValue(); return field; }

Concurrency in Java More Item 71: Double Check Lazy Initialization // Double-check idiom for lazy initialization of instance fields private volatile FieldType field; // volatile key – see Item 66 FieldType getField() { FieldType result = field; if (result == null) { // check with no locking synchronized (this) { result = field; if (result == null) // Second check with a lock field = result = computeFieldValue(); } return result; }

Concurrency in Java Item 72: Don’t Depend on the Thread Scheduler Any program that relies on the thread scheduler is likely to be unportable Threads should not busy-wait Use concurrency facilities instead (Item 69) Don’t “Fix” slow code with Thread.yield calls Restructure instead Avoid Thread priorities

Concurrency in Java Item 73: Avoid Thread Groups Thread groups originally envisioned as a mechanism for isolating Applets for security purposes Unfortunately, doesn’t really work