Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.

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)
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
ThreadThread Thread Basics Thread Synchronization Animations.
© 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.
More Multithreaded Programming in Java David Meredith Aalborg University.
Concurrency with Java Varadha Sundaram. Programming Paradigms Single Process Multi Process Multi Core/Multi Thread.
50.003: Elements of Software Construction Week 5 Basics of Threads.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Internet Software Development More stuff on Threads Paul Krause.
Threads some important concepts Simon Lynch
1 Java Threads and Synchronization Review Modified from slides taken from
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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)
Concurrency Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a.
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.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CMSC 330: Organization of Programming Languages Threads.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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 Java Programming Java Programming II Concurrent Programming: Threads ( II)
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.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Distributed and Parallel Processing George Wells.
Java Thread Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multithreading.
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Multithreading Chapter 23.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Java Based Techhnology
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Threads in Java James Brucker.
Multithreading in java.
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Concurrency in Java Brad Vander Zanden

Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares the process’s resources with other threads

Java’s Thread Mechanism Low Level – Thread Class – Runnable Interface High Level: Thread executors and tasks

Runnable Interface public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); }

Subclassing Thread public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); }

Thread vs. Runnable Runnable allows you to subclass another object Thread is more direct and a bit simpler

Pacing a Thread Thread.sleep(ms) suspends execution for the specified period – gives up processor – allows thread to pace execution, such as when doing an animation

Handling Interrupts Interrupt() method may be invoked on a thread to notify it of an interrupt Ways to handle an interrupt – Catch InterruptedException: Thrown by methods like sleep and wait – Call Thread.interrupted() Interrupt status flag – Checked by interrupted – Cleared by InterruptedException or by calling interrupted()

Examples for (int i = 0; i < importantInfo.length; i++) { // Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { // We've been interrupted: no more messages. return; } // Print a message System.out.println(importantInfo[i]); }

Examples for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { // We've been interrupted: no more crunching. return; }

Join The join method allows one thread to wait for the completion of another thread Example: t.join() waits for the thread referenced by t to finish execution

A Detailed Example //docs.oracle.com/javase/tutorial/essential/co ncurrency/simple.html //docs.oracle.com/javase/tutorial/essential/co ncurrency/simple.html

Synchronization Why we need it – Thread interference: contention for shared resources, such as a counter – Memory inconsistency: if there is a happens- before relationship where thread A relies on thread B performing a write before it does a read joins are a trivial way to handle memory inconsistency

Synchronization Techniques Synchronized Methods Synchronized Statements/Locks Volatile Variables

Synchronized Methods public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; }

Problem w/o Synchronization The single expression c++ can be decomposed into three steps: 1.Retrieve the current value of c. 2.Increment the retrieved value by 1. 3.Store the incremented value back in c.

A Bad Interleaving of Operations A possible interleaving of Thread A and B – Thread A: Retrieve c. – Thread B: Retrieve c. – Thread A: Increment retrieved value; result is 1. – Thread B: Decrement retrieved value; result is -1. – Thread A: Store result in c; c is now 1. – Thread B: Store result in c; c is now -1.

Synchronized Statements public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); }

Example with Multiple Locks public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; }} public void inc2() { synchronized(lock2) { c2++; }} }

Volatile Variables Example: volatile int x1; Forces any change made by a thread to be forced out to main memory Ordinarily threads maintain local copies of variables for efficiency

Synchronized Method vs Volatile Variables synchronized methods – force all of a thread’s variables to be updated from main memory on method entry – flush all changes to a thread’s variables to main memory on method exit – obtain and release a lock on the object volatile variable – only reads/writes one variable to main memory – does no locking

Happens-Before Using Wait Object.wait(): suspends execution until another thread calls notifyAll() or notify() Must check condition because notifyAll/notify does not specify which condition has changed – Use notify for a mutex where only one thread can use the lock – Use notifyAll for situations where all threads might be able to usefully continue

Example public synchronized guardedJoy() { // keep looping until event we’re // waiting for happens while(!joy) { try { wait(); } catch (InterruptedException e) {} } System.out.println("Joy and efficiency have been achieved!"); } public synchronized notifyJoy() { joy = true; notifyAll(); } Thread 1Thread 2

Producer-Consumer Example al/concurrency/guardmeth.html al/concurrency/guardmeth.html

High Level Java Concurrency Mutex Locks Executors Concurrent collections Atomic variables Random number generation

Mutex Locks lock interface – lock(): acquires a lock and sleeps if necessary – tryLock(ms): tries to acquire a lock returns true on success and false on failure can specify optional ms, in which case it will timeout after that length of time tryLock allows thread to back out without sleeping if lock is unavailable – unlock(): releases the lock – lockInterruptibly(): like lock but allows thread to be interrupted while waiting by throwing InterruptedException

Mutex Example Alphonse and Gaston bowing to one another: al/concurrency/newlocks.html al/concurrency/newlocks.html

Tasks and Thread Pools A task is a computation that you want repeated one or more times – it should be embedded in a thread A thread pool is a pool of one or more worker threads to which tasks may be assigned When a task is submitted to a thread pool, it is placed on a queue and ultimately executed by one of the worker threads

Executors Executors manage thread pools – Executor, a simple interface that supports launching new tasks. – ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself. – ScheduledExecutorService, a subinterface of ExecutorService, supports future and/or periodic execution of tasks.

Executor Class The Executor class provides a collection of factory methods that create thread pools which are managed using one of the three desired executor interfaces

Executor Interface allows you to submit Runnable tasks to a thread pool via the execute method

ExecutorService allows you to submit either Runnable or Callable tasks via the submit method – Callable tasks may return a value. This value may be retrieved using the Future object returned by the submit method. – The Future object represents the pending result of that task. You access the result using the get() method. The thread will wait until the result is returned The Future object also allows you to cancel the execution of the task

ExecutorService (cont) allows you to shutdown a thread pool – shutdown(): accepts no new tasks but finishes execution of all running and waiting tasks – shutdownNow() accepts no new tasks kills waiting tasks tries to kill running tasks by calling interrupt(): up to each task as to whether or not they actually die

ExecutorService (cont) can submit a collection of tasks for execution using invokeAll() method – returns a list of Future object that can be monitored for task completion – takes a collection object as a parameter

ScheduledExecutorService Allows you to schedule repeating tasks – fixed rate: execute every n time units (useful for clocks) – fixed delay: execute every n time units after the termination of the current task (can cause drift in a clock) Can cancel a repeating task by calling cancel on its returned Future object

ScheduledExecutorService Also allows you to schedule a one-shot task at a future time

Example The following example prints “beep” every 10 seconds for an hour util/concurrent/ScheduledExecutorService.html