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

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
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.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Threads in C# Threads in C#.
1 CS2200 Software Development Lecture: Multi-threading II A. O’Riordan, 2009.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
Java 5 Threading CSE301 University of Sunderland Harry Erwin, PhD.
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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Threads some important concepts Simon Lynch
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
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.
Threading Eriq Muhammad Adams J
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 in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
1 G53SRP: Clocks and Time in Java Chris Greenhalgh School of Computer Science.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
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.
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.
A brief intro to: Parallelism, Threads, and Concurrency
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Multithreaded Programming in Java
Critical sections, locking, monitors, etc.
Threads Chate Patanothai.
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.
Computer Science 2 06A-Java Multithreading
Threads in Java James Brucker.
Threads and Multithreading
9. Threads SE2811 Software Component Design
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

Benefits of threads More CPU’s Many modern computers has more than one CPU –Dual Core By dividing the program into more threads the program can utilize the CPU’s –The program will run faster Threads in Java2

Benefits of threads A thread may be waiting for something to happen –File to be read –Incoming network requests –Sleep() –Wait() While one thread is waiting other threads should use the CPU –The program will run faster Figure from – 09/07/process-concept-operating- system.html Threads in Java3

4 Creating threads Class A extends Thread { public void run() { … } A a = new A(); a.start(); Class A can not extend other classes. Class B implements Runnable { public void run() { … } B b = new B(); Tread t = new Thread(b); t.start(); Class B may extend another class. Decouples task submission from thread scheduling, etc.

Threads in Java5 Joining treads Some methods on the class Thread –start() Starts the thread –join() waits for the thread to die Runnable printerA = new Printer("Anders", 10); Thread threadA = new Thread(printerA); threadA.start(); // threadA.join(); System.out.println( "Main is done");

Interrupting threads You can interrupt a thread. An interrupted thread should stop doing what it is doing, and do something else. –Like stop running Example –Interrupting (NetBeans project) Threads in the “waiting state” receives an InterruptedException –Thrown by sleep(), etc. A thread may ask if it has been interrupted –boolean Thread.interrupted() –Static method in the Thread class (like sleep(…)) Threads in Java6

7 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 Java8 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 Java9 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 Java10 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 Java11 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 Java12 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 Java13 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() Example –ThreadBank, package waitingacccount

Threads in Java14 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 Java15 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 Java16 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 Java17 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 Java18 Callable vs. runnable interface Callable has 1 method –V call() throws Exception –Can return a value –Can throw exceptions Can be executed using an Executor object Runnable has 1 method –void run() –No return value –No exceptions Can be executed using an Executor object

Threads in Java19 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 Java20 Threads in Java Swing Java Swing has a single thread –Called the event-dispatching-thread (EDT) –Event-handling –Painting visual components –Creating and showing the GUI should be executed by the EDT To avoid deadlock

Threads in Java21 Methods in javax.swing.Utilities The class javax.swing.Utilities has 2 interesting static methods –SwingUtilities.invokeLater(Runnable r) Returns as soon as r is handed over to the EDT. –Asynchronous Used for updating visual components. –SwingUtilities.invokeAndWait(Runnable r) Returns when r has finished running –Synchronous

Threads in Java22 Starting a Swing based application class MyFrame extends JFrame { … } public static void main(String [] args) { Runnable r = new Runnable() { // anonymous inner class public void run() { new MyFrame().setVisible(); } SwingUtilities.invokeLater(r); } This is (almost) the code NetBeans generates when you make a new JFrame class!

Threads in Java23 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 –Example longRunningThread calling run() vs. start()

Threads in Java24 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 Java25 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