50.003: Elements of Software Construction Week 10 Thread Pool.

Slides:



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

50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
CS 443 Advanced OS Fabián E. Bustamante, Spring 2005 Resource Containers: A new Facility for Resource Management in Server Systems G. Banga, P. Druschel,
CSC Multiprocessor Programming, Spring, 2011 Outline for Chapter 6 – Task Execution Dr. Dale E. Parson, week 7.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
1 Thread Pools Representation and Management of Data on the Internet.
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 5: Threads Overview Multithreading Models Threading Issues Pthreads Solaris.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Lecture 10 – Using Thread Pools Housekeeping:  exam return Monday  Programming assignment on Monday Purpose: practice use of the mechanisms we’ve discussed.
Server Architecture Models Operating Systems Hebrew University Spring 2004.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L20 (Chapter 24) Multithreading.
Multithreading.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Concurrency Patterns Emery Berger and Mark Corner University.
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.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Dynamic Architectures (Component Reconfiguration) with Fractal.
OPERATING SYSTEM SUPPORT DISTRIBUTED SYSTEMS CHAPTER 6 Lawrence Heyman July 8, 2002.
14.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 4: Threads.
Synchronizing threads, thread pools, etc.
Practical Session 12 Reactor Pattern. Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Computer Science 313 – Advanced Programming Topics.
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.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Middleware Services. Functions of Middleware Encapsulation Protection Concurrent processing Communication Scheduling.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Project 2 Overview (Threads in Practice) CSE451 Andrew Whitaker.
CSC Multiprocessor Programming, Spring, 2012 Chapter 8 – Applying Thread Pools Dr. Dale E. Parson, week 10.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
…in java DThread Pools x. Thread Pools: Why? Source code updates – copy/paste of run/runnable method for each thread is exhausting There is overhead to.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Today Threading, Cont. Multi-core processing. Java Never Ends! Winter 2016CMPE212 - Prof. McLeod1.
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Processes and Threads Processes and their scheduling
Operating System (013022) Dr. H. Iwidat
Distributed Systems - Comp 655
Multithreading.
Android Topics UI Thread and Limited processing resources
Threads in Java James Brucker.
Concurrency, Processes and Threads
Chapter 4: Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

50.003: Elements of Software Construction Week 10 Thread Pool

How many threads should I use? What should each thread do?

Plan of the Week Executing tasks in threads The Executor framework Applying thread pools

Tasks Most concurrent applications are organized around the execution of tasks: abstract, discrete units of work. Designing your program organization around tasks – Identify sensible task boundaries – Ideally, tasks are independent activities: work that does not depend on other tasks – Independence facilitates concurrency

Example: Server Most server applications offer a natural choice of task boundary: individual client requests. Executing tasks sequentially This might work if handleRequest returns immediately – not for real world web server. public class SingleThreadWebServer { public static void main (String[] args) throws Exception { ServerSocket socket = new ServerSocket(80); while (true) { Socket connection = socket.accept(); handleRequest(connection); }

One Thread Per Task A more responsive approach is to create a new thread for servicing each request class ThreadPerTaskWebServer { public static void main (String[] args) throws Exception { 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(); }

One Thread Per Task Task processing is offloaded from the main thread – more responsive. Tasks can be processes in parallel – improved throughput. Task-handling code must be thread-safe, because it may be invoked concurrently for multiple tasks. It works under light or moderate load.

Unbound Thread Creation For production purposes (large webservers for instance) task-per-thread has some drawbacks. – Thread creation and tear down involves the JVM and OS. For lots of lightweight threads this is not very efficient. – Active Threads consume extra memory, for instance to provide for a thread stack. – If there are less CPU's than threads, some threads sit idle, consuming memory. – There is a limit on how many threads you can have concurrently. If you hit this limit your program will most likely become unstable.

Cohort Exercise 1 (10 min) Given MultipleClient.java and WebServer.java, implement the sequential server and one thread per task server and compare their performance. Vary the number of threads (10,100,1000) and see the trend. Work in pairs (one as the clients and the other as the server). Sample program: SingleThreadWebServer.java ThreadPerTaskWebServer.java

The Executor Framework Single thread – poor responsiveness and throughput Thread-per-task – Poor resource management (consider a deny of service attack) The executor framework offers flexible thread pool management

Task as Executor Executor provides a standard means of decoupling task submission from task execution. – The Runnable is the task itself. – The method execute defines how it is executed. public interface Executor { void execute (Runnable command); } Click here for a sample program: ExecutorWebServer.java

Execution Policy Decoupling submission from execution is that it lets you specify the execution policy for a given class of tasks. – In what thread will tasks be executed? – In what order should tasks be executed (FIFO)? – How many tasks may execute concurrently? – How many tasks may be queued pending execution? – If a task has to be rejected because the system is overloaded, which task should be selected and how the application be notified? – What actions should be taken before or after executing a task? Click here for a sample program: SequentialExecutorWebServer.java ThreadPerTaskExecutorWebServer.java

Thread Pools tasksthread pool execution policy define as Runnable of each Executor object Define in Execute() of the executor class task queue

Advantage of Thread Pools Reusing an existing thread; reduce thread creation and teardown costs. No latency associated with thread creation; improves responsiveness. By properly tuning the size of the thread pool, you can have enough threads to keep the processors busy while not having so many that your application runs out of memory or thrashes due to competition among threads for resources

Thread Pool Implementations newFixedThreadPool – Fixed-size thread pool; creates threads as tasks are submitted, up to the maximum pool size and then attempts to keep the pool size constant newCachedThreadPool – Boundless, but the pool shrinks and grows when demand dictates so newSingleThreadExecutor – A single worker thread to process tasks, sequentially according to the order imposed by the task queue newScheduledThreadPool – A fixed-size thread pool that supports delayed and periodic task execution.

Cohort Exercise 2 (15 min) Given MultipleClient.java (with the smaller number), complete ExecutorWebServer.java using newFixedThreadPool with 100 threads. Compare the performance with the sequential and thread-per-task web server (with 10, 100, 1000 client threads). Click here for a sample program: FactorExecutorWebServer.java

Executor Lifecycle Shut down an Executor through ExecutorService public interface ExecutorService extends Executor { void shutdown(); List shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; // … additional convenience methods for task submission }

shutdown() vs shutdownNow() shutdown() – will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run shutdownNow() – will do the same AND will try to cancel the already submitted tasks by interrupting the relevant threads. Note that if your tasks ignore the interruption, shutdownNow() will behave exactly the same way as shutdown().

Cohort Exercise 3 (15 min) Given LifecycleWebServer.java, modify it such that it can be shut down through a client request by sending the server a specially formatted request. Test your program. Click here for a sample program: LifeCycleWebShutDownServer.java

Task Coupling and Execution Policy Thread pools work best when tasks are homogeneous and independent. – Dependency between tasks in the pool creates constraints on the execution policy which might result in problems (deadlock, liveness hazard, etc.) – Long-running tasks may impair the responsiveness of the service managed by the Executor. – Reusing threads create channels for communication between tasks – don’t use them.

Sizing Thread Pools The ideal size for a thread pool depends on the types of tasks and the deployment system – If it is too big, performance suffers – If it is too small, throughput suffers Heuristics – For compute intensive tasks, N+1 threads for a N- processor system – For tasks including I/O or other blocking operations, you want a larger pool

Optimal CPU Utilization Given these definitions: N = number of CPUs U = target CPU utilization W/C = ratio of wait time to compute time The optimal pool size is: M = N * U * (1 + W/C) The number of CPUs can be obtained by: Runtime.getRuntime().availableProcessors()

Cohort Exercise 4 (10 min) Given MultipleClient.java (with the bigger number and 5 clients) and ExecutorWebServer.java, tune the thread pool size in the factor web server example for optimal performance.

Sizing the Queue tasksthread pool execution policy task queue The queue may grow unbounded! When a bounded task queue fills up, the saturation policy comes into play. The default: throw RejectedExecutionException

More Than CPUs Other resources that can contribute to sizing constraints are memory, file handles, socket handles, database connections, etc. – Add up how much of those resources each task requires and divide that into the total quantity available Alternatively, the size of the thread pool can be tuned by running the application using different pool sizes and observing the level of CPU and other resource utilization.