1 (Worker Queues) cs236607. 2 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.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Deadlock and Starvation
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)
Concurrency 101 Shared state. Part 1: General Concepts 2.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
Multithreading The objectives of this chapter are:
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.
Multithreading.
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.
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
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
The Alternative Larry Moore. 5 Nodes and Variant Input File Sizes Hadoop Alternative.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
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.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
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.
Java Thread and Memory Model
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.
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 Two ways to start a thread
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
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.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Distributed Systems - Comp 655
Multithreading Chapter 23.
Multithreading.
Software Engineering and Architecture
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 (Worker Queues) cs236607

2 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

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

4 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

5 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

6 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

7 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

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

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

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

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

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

13 Task Queue Worker Threads A Possible Solution cs When a task ends, the thread is released 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)

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

15 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

16 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

17 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

18 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…) cs

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 cs

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

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 cs

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) cs

cs 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(); } }

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