Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.

Slides:



Advertisements
Similar presentations
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
Advertisements

Operating Systems Lecture 7.
50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
50.003: Elements of Software Construction Week 10 Thread Pool.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
CSC Multiprocessor Programming, Spring, 2011 Outline for Chapter 6 – Task Execution Dr. Dale E. Parson, week 7.
Concurrency 101 Shared state. Part 1: General Concepts 2.
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.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Assignment – no class Wednesday All: watch the Google Techtalk “Getting C++ Threads Right” by Hans Boehm at the following link in place of Wednesday’s.
Concurrency CS 510: Programming Languages David Walker.
Lecture 10 – Using Thread Pools Housekeeping:  exam return Monday  Programming assignment on Monday Purpose: practice use of the mechanisms we’ve discussed.
Synchronization in Java Fawzi Emad Chau-Wen Tseng 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.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
Week 9 Building blocks.
I/O Systems ◦ Operating Systems ◦ CS550. Note:  Based on Operating Systems Concepts by Silberschatz, Galvin, and Gagne  Strongly recommended to read.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Optimistic Design 1. Guarded Methods Do something based on the fact that one or more objects have particular states  Make a set of purchases assuming.
Internet Software Development Controlling Threads Paul J Krause.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Chapter 7 -1 CHAPTER 7 PROCESS SYNCHRONIZATION CGS Operating System Concepts UCF, Spring 2004.
Concurrency & Context Switching Process Control Block What's in it and why? How is it used? Who sees it? 5 State Process Model State Labels. Causes of.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
CSC Multiprocessor Programming, Spring, 2012 Chapter 11 – Performance and Scalability Dr. Dale E. Parson, week 12.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
CSC Multiprocessor Programming, Spring, 2012 Chapter 8 – Applying Thread Pools Dr. Dale E. Parson, week 10.
CSC Multiprocessor Programming, Spring, 2012 Outline for Chapter 4 – Composing Objects – thread-safe object-oriented composition, Dr. Dale E. Parson,
Operating System Concepts
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.
Introduction to operating systems What is an operating system? An operating system is a program that, from a programmer’s perspective, adds a variety of.
Lecturer 3: Processes multithreaded Operating System Concepts Process Concept Process Scheduling Operation on Processes Cooperating Processes Interprocess.
1 Announcements HW8 due today HW9: Java Concurrency Will post tonight Due May 9 th Java infrastructure Download the Eclipse IDE Rainbow grades HW 1-6 Exam.
Tutorial 2: Homework 1 and Project 1
Multithreading / Concurrency
Processes and threads.
Thread Pools (Worker Queues) cs
Threads vs. Events SEDA – An Event Model 5204 – Operating Systems.
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Task Scheduling for Multicore CPUs and NUMA Systems
Threads, Concurrency, and Parallelism
Synchronization Lecture 23 – Fall 2017.
Race Conditions & Synchronization
Threads Chapter 4.
Java Concurrency 17-Jan-19.
Process Description and Control
Java Concurrency.
Java Concurrency.
CSE 451 Section 1/27/2000.
Java Concurrency 29-May-19.
CSC Multiprocessor Programming, Spring, 2011
Threads and concurrency / Safety
Presentation transcript:

Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design for thread safety  Identify variables that form object’s state  Identify invariants on these states  Establish policy for managing concurrent access  Objects and variables have a state space  Smaller, the better

State-dependent operations  Current state dependent on previous state  cannot remove item from empty queue  Single threaded  Precondition does not hold  Operation fails  Concurrent  Precondition may become true later  Wait for action by another thread  Precondition may be invalidated as well

Instance confinement  Encapsulation of data  Object’s methods will access the data  Ensure data is accessed with appropriate lock held  Not escape intended scope  Monitor pattern  Encapsulate all mutable state  Use object’s own intrinsic lock to guard the state Public class PrivateLock { private final Object myLock = new Object(); Widget widget; void someMethod() { synchronized(myLock) { …. } }

Summary  Mutable state  Coordinating access to mutable state  Less mutable, easier to ensure thread safety  Make fields final  If they need not be mutable  Immutable objects are thread-safe  Encapsulation helps thread-safety  Mutable state  Guard with a lock (and the same lock everywhere)  Compound actions are guarded together

Summary (contd)  Mutable variable from multiple threads with no synchronization  Broken program  Include thread-safety in design process  Explicit documentation  Document synchronization policy

Structuring concurrent applications  Tasks  Abstract, discrete unit of works  Benefits  Simplifies program organization  Facilitates error recovery  Promotes concurrency  Natural structure for parallelizing work  Independent activities  State, result or side-effects of other tasks  Each task represents fraction of application processing capacity

Executing tasks sequentially Class WebServer { public static void main(…) { ServerSocket socket = new ServerSocket(80); while(true) { Socket connection = socket.accept(); handleRequest(connection); }  Simple and correct  Perform poorly in production  Might work if handleRequest returned immediately

Explicitly creating threads for tasks Class WebServer { …. Serversocket socket = new ServerSocket(80); while(true) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handleRequest(connection); } }; new Thread(task).start(); }  For each connection, new thread is created

Consequences  Task processing is offloaded from main thread  Wait for new connections  Tasks can be processed in parallel  Multiple requests serviced simultaneously  Task-handling code must be thread-safe

Disadvantages of unbounded thread creation  Thread lifecycle overhead  Thread creation  Thread teardown  Resource consumption  Threads consume resources  Some threads may sit idle consuming resources  Stability  Limit on how many threads can be created  OutOfMemoryError is possible

Decoupling  Tasks are logical units of work  Threads to run tasks asynchronously  Decouple task submission and task execution  Task submission – producer  Task execution – consumer  Pre-determined number of threads created  Testing possible for stability  Bounded queue of tasks

Execution policies  In what thread will tasks be executed  Order of execution of tasks  Concurrent tasks  Queuing length of the tasks  Task that should be evicted  How application should be notified  Action before/after executing a task

Cancellation and shutdown  Stop tasks/threads earlier  How?  Immediately?  Why?  User requested cancellation  Time-limited activities  Best solution within a time  Application events  Decomposition of problem space  Errors  e.g., disk full  Shutdown

Task cancellation  public void foo() {  while(!cancelled) {  doSomething(); } public void bar() { cancelled = true; }  Eventually foo() exits  What is the type of cancelled?

Interruption  Each thread has a boolean interrupted status  Some blocking methods detect interrupts and return early with exception  Well behaved methods  Return the interrupt status to the calling method to handle  Poorly behaved methods  Swallow the interrupts  Interruption policy  How thread should interpret interrupt?  What needs to be done?  What units of work are considered atomic?  Time of reaction to interrupts

Thread Pools  Dependent tasks  Constraints on execution policy  Avoid liveness problems  Tasks that exploit thread confinement  Single threaded executor  Thread safety is not required  Response-time sensitive tasks  Long running tasks to thread pool with few threads  Tasks that use ThreadLocal  Not to be used to communicate between tasks

Thread Pools (contd.)  Thread starvation deadlock  Tasks depend on other tasks in thread pool  Second task sits on work queue  First task waits for result of second task  Long-running tasks  Fewer threads in thread pool  Responsiveness suffers

Sizing thread pools  Ideal size  Type of submitted tasks  Characteristics of the deployment system  Not hard-coded  Computed dynamically  Configuration mechanism  Too big  Threads compete for resources  Too small  Throughput suffers

Sizing thread pools (contd.)  Number of processors  Amount of memory  Type of task  Computation  I/O  Some combination  Requires scarce resource  Compute-intensive tasks  N+1 threads on N processor system  I/O based tasks  More threads in the pool

Optimal pool size  N_cpu = number of CPUs  U_cpu = target CPU utilization, 0 <= U_cpu <= 1  W/C = ratio of wait time to compute time N_threads = N_cpu * U_cpu * (1 + W/C)  Other parameters  Memory, file handles, etc