Thread Pools (Worker Queues) cs236607.

Slides:



Advertisements
Similar presentations
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Advertisements

50.003: Elements of Software Construction Week 10 Thread Pool.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Concurrency 101 Shared state. Part 1: General Concepts 2.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
1 Thread Pools Representation and Management of Data on the Internet.
Server Architecture Models Operating Systems Hebrew University Spring 2004.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Threads. Introduction Process 1 Processes and Threads Environment Stack Code Heap CPU State Process 2 Environment Stack Code Heap CPU State.
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).
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Threads Written by Amir Kirsh, Dr. Yaron Kanza. Edited by Liron Blecher.
Fundamentals of Python: From First Programs Through Data Structures
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Threads some important concepts Simon Lynch
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
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.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Threading Eriq Muhammad Adams J
Dynamic Architectures (Component Reconfiguration) with Fractal.
Synchronizing threads, thread pools, etc.
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.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.
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.
…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.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Doing Several Things at Once
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Thread Pools (Worker Queues) cs
Practice Session 8 Lockfree LinkedList Blocking queues
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Java Programming Language
Lecture 21 Concurrency Introduction
Threads and Concurrency in Java: Part 2
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Threads II IS
Distributed Systems - Comp 655
Multithreading Chapter 23.
Condition Variables and Producer/Consumer
Operating System Concepts
Multithreading.
Condition Variables and Producer/Consumer
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Using threads for long running tasks.
Software Engineering and Architecture
some important concepts
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Thread Pools (Worker Queues) cs236607

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 a new thread for every client request Instead, the server uses an already prepared thread if there is a free one, or waits until there is a free thread cs236607

Why Do We Need a Thread Pool? Why not to span a thread upon each request? Server thread thread thread To which cases such an architecture is suitable? cs236607

Why Using Thread Pools? Thread pools improve resource utilization The overhead of creating a new thread is significant Thread pools enable applications to control and bound their thread usage Creating too many threads in one JVM can cause the system to run out of memory and even crash There is a need to limit the usage of system resources such as connections to a database cs236607

Thread Pools in Servers Thread pools are especially important in client-server applications The processing of each individual task is short-lived and the number of requests is large Servers should not spend more time and consume more system resources creating and destroying threads than processing actual user requests When too many requests arrive, thread pools enable the server to force clients to wait until threads are available cs236607

The “Obvious” Implementation There is a pool of threads Each task asks for a thread when starting and returns the thread to the pool after finishing When there are no available threads in the pool the thread that initiates the task waits till the pool is not empty What is the problem here? “Synchronized” model - the client waits until the server takes care of its request… cs236607

The “Obvious” Implementation is Problematic When the pool is empty, the submitting thread has to wait for a thread to be available We usually want to avoid blocking that thread A server may want to perform some actions when too many requests arrive Technically, Java threads that finished running cannot run again cs236607

All the worker threads wait for tasks A Possible Solution Every thread looks for tasks in the queue wait() Task Queue Worker Threads If Q is Empty All the worker threads wait for tasks cs236607

A Possible Solution Task Task Queue Worker Threads “A-synchronized” model: “Launch and forget” The number of worker threads is fixed. When a task is inserted to the queue, notify is called cs236607

A Possible Solution Task Task Queue Worker Threads notify() Task Task Queue Worker Threads The number of worker threads is fixed. When a task is inserted to the queue, notify is called cs236607

A Possible Solution The task is executed by the thread Task Queue Worker Threads cs236607

A Possible Solution The task is executed by the thread Task Queue Worker Threads The remaining tasks are executed by the other threads cs236607

A Possible Solution When a task ends, the thread is released Task Queue Worker Threads While the Q is not empty, take the task from the Q and run it (if the Q was empty, wait() would have been called) cs236607

A Possible Solution A new task is executed by the released thread Task Queue Worker Threads cs236607

Thread Pool Implementation public class TaskManager { LinkedList taskQueue = new LinkedList(); List threads = new LinkedList(); public TaskManager(int numThreads) { for(int i=0; i<numThreads; ++i) { Thread worker = new Worker(taskQueue); threads.add(worker); worker.start(); }} public void execute(Runnable task) { synchronized(taskQueue) { taskQueue.addLast(task); taskQueue.notify(); } } } cs236607

Thread Pool Implementation public class Worker extends Thread { LinkedList taskQueue = null; public Worker(LinkedList queue) { taskQueue = queue; } public void run() { Runnable task = null; while (true) { synchronized (taskQueue) { while (taskQueue.isEmpty()) { try {taskQueue.wait();} catch (InterruptedException ignored) {}} task = (Runnable) taskQueue.removeFirst(); } task.run(); }}} cs236607

Risks in Using Thread Pools Threads can leak A thread can endlessly wait for an I/O operation to complete For example, the client may stop the interaction with the socket without closing it properly What if task.run() throws a runtime exception (as opposed to other exceptions that a programmer of a client application has to catch in order to succeed compiling)? Solutions: Bound I/O operations by timeouts using wait(time) Catch possible runtime exceptions cs236607

Pool Size What is better: to have a large pool or a small pool? Each thread consumes resources memory, management overhead, etc. A large pool can cause starvation Incoming tasks wait for a free thread A small pool can cause starvation Therefore, you have to tune the thread pool size according to the number and characterizations of expected tasks There should also be a limit on the size of the task queue (why?) cs236607

Handling too Many Requests What is the problem with the server being overwhelmed with requests? What can a server do to avoid a request overload? Do not add to the queue all the requests: ignore or send an error response Use several pool sizes alternately according to stress characteristics (but do not change the size too often…) cs236607

Tuning the Pool Size The main goal: Processing should continue while waiting for slow operations such as I/O WT = estimated average waiting time ST = estimated average processing time for a request (without the waiting time) About WT/ST+1 threads will keep the processor fully utilized For example, if WT is 20 ms and ST is 5 ms, we will need 5 threads to keep the processor busy cs236607

The java.util.concurrent Package Provides a more advanced mechanisms for handling concurrency (Since Java 5.0) Includes an implementation of thread pools cs236607

Lock Synchronized sections are like a trap – once entered, the thread is blocked till … Lock objects provide the ability to check the availability of the lock and back out, if desired When using Lock objects, lock() and , unlock() are called explicitly cs236607

Executor The class Executors has 2 static methods to create thread pools ExecutorService newFixedThreadPool(int nThreads) Pool of a fixed size ExecutorService newCachedThreadPool() Creates new threads as needed New threads are added to the pool, and recycled ExecutorService has an execute method void execute(Runnable command) cs236607

class NetworkService { private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException { serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); } public void serve() { try { for (;;) { pool.execute(new Handler(serverSocket.accept())); } } catch (IOException ex) { pool.shutdown(); } cs236607

private final Socket socket; Handler(Socket socket) { class Handler implements Runnable { private final Socket socket; Handler(Socket socket) { this.socket = socket; } public void run() { // read and service request } } cs236607