Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.

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

Operating Systems Part III: Process Management (Process Synchronization)
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Practice Session 7 Synchronization Liveness Guarded Methods Model
COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?
CS 11 java track: lecture 7 This week: Web tutorial:
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
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.
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 CS2200 Software Development Lecture: Multi-threading II A. O’Riordan, 2009.
Software Engineering Oct-01 #11: All About Threads Phil Gross.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
More Multithreaded Programming in Java David Meredith Aalborg University.
Multithreading.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Threads some important concepts Simon Lynch
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
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 Concurrent Languages – Part 1 COMP 640 Programming Languages.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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.
Internet Software Development Controlling Threads Paul J Krause.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Synchronizing threads, thread pools, etc.
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 in Java1 Concurrency Synchronizing threads, thread pools, etc.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
CSC 660: Advanced Operating SystemsSlide #1 CSC 660: Advanced OS Synchronization.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
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.util.concurrent package. concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as.
Tutorial 2: Homework 1 and Project 1
A brief intro to: Parallelism, Threads, and Concurrency
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Background on the need for Synchronization
Multithreaded Programming in Java
Critical sections, locking, monitors, etc.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Multithreading.
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Computer Science 2 06A-Java Multithreading
CS703 – Advanced Operating Systems
CSE 332: Concurrency and Locks
Software Engineering and Architecture
some important concepts
Presentation transcript:

Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.

Life Cycle of threads Threads in Java2

3 Synchronizing threads Having threads in a programming language is a nice feature, but threads must to be controlled. –If you have 2 or more threads with reference to the same object, the threads might execute methods on that object simultaneously. This must be controlled

Threads in Java4 Race conditions and critical sections Race condition –2 or more threads are reading or writing shared data and the final result depends on the timing of the thread scheduling. –Race conditions are generally a bad thing! Critical section –Part of a program (whole method or just a part of a method) where race conditions might happen. –To avoid race conditions We want to make sure that at most one thread executes the critical section at any point in time. Threads must be synchronized.

Threads in Java5 Locks on objects Every object has an associated lock. At most one thread can have the lock at any point in time. A thread acquire the lock of the object when it enters a synchronized block (i.e. critical section) –If another thread holds the lock on the object the entering thread has to wait (hopefully not forever). A thread releases the lock when it leaves the synchronized block.

Threads in Java6 Synchronization: Java syntax public synchronized method() { // critical section } Often the whole method is a critical section. You synchronize on the current object, i.e. this. public method() { … synchronized(obj) { // critical section } … } Sometimes only part of a method is a critical section. You synchronize on the object mentioned. Less synchronization, means more concurrency.

Threads in Java7 Reentrant locks If a thread has a the lock on some object, and then calls another synchronized method, –The thread does not have to wait for itself to release the lock –The lock is not released when it leaves the latter method Since the thread had the lock before entering the method.

Threads in Java8 wait Entering a synchronized method a thread might realize that it is not in a state to fulfill its task – and it cannot simply return from the method because the return value is not “ready”. The thread must wait –Call wait() Method from class Object wait() really means this.wait() Releases the lock on the object –Another thread can run, hopefully “fixing the state” Waits for another thread to call a notify() or notifyAll()

Threads in Java9 notify() and notifyAll() obj.notify() –Wakes up a single thread waiting on obj. The thread is randomly chosen obj.notifyAll() –Wakes up all threads waiting on obj. –Generally you want to use notifyAll() not notify()

Threads in Java10 Wait “Code pattern” synchronized (obj) { while (conditionDoesNotHold) { obj.wait(); } // perform action appropriate to the condition } urrency/guardmeth.htmlhttp://download.oracle.com/javase/tutorial/essential/conc urrency/guardmeth.html wait() should always be called in a loop, since obj.notifyAll() wakes up all thread waiting for the object. Only the first (quickest) should execute the synchronized block. Other thread go back to wait.

Threads in Java11 3 versions of wait wait() –Waits indefinitely for notification hopefully not forever wait(long timeout) –Waits for notification or until timeout milliseconds has elapsed wait(long timeout, int nanos) –Waits for notification or until timeout milliseconds + nanos nanoseconds have elapsed.

Threads in Java12 Collection framework Vector and HashTable –Old collections From before the collections framework –Methods are synchronized Synchronized wrappers –Modern collections like List, Set, and Map From the collections framework –Methods are not synchronized –Methods can be synchronized using the synchronized wrappers Static methods in class Collections –Collection synchronizedCollection( Collection c ) –List synchronizedList( List l ) –Set synchronizedSet( Set s ) –Map synchronizedMap( Map m )

Threads in Java13 Thread pools Creating a new thread object takes relatively much time Idea: Recycle thread objects. –Keep threads in a thread pool. –Request thread from pool. –Put used threads back into the pool. –java.util.concurrent offers more implementations of this idea New in Java 5.0 Example – rrent/ExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concu rrent/ExecutorService.html

Threads in Java14 Thread pool implementations The class Executors has 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)

Threads in Java15 Use threads to improve performance Move time-consuming tasks out of the main thread –GUI responds faster –Create special threads for the time-consuming tasks. –Examples: Reading data from files, network connections, databases, etc. Long running computations

Threads in Java16 References Sun Microsystems The Java Tutorial, Threads – mlhttp://java.sun.com/docs/books/tutorial/essential/threads/index.ht ml Sun Microsystems Java 2 Platform Standard Edition 5.0 API Specification: java.util.concurrent – ge-summary.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/packa ge-summary.html

Threads in Java17 More references Brian Goetz et al Java Concurrency in Practice, Addison Wesley Doug Lea Concurrent Programming in Java 2 nd edition, Addison Wesley 2000 Oaks & Wong Java Threads, O’Reilly 2004 Niemeyer & Knudsen Learning Java, 3 rd edition, O’Reilly 2005 –9. Threads, page