COMP 322: Fundamentals of Parallel Programming

Similar documents
Lecture 29: Java s synchronized statement

Lecture 24: Java Threads,Java synchronized statement

COMP 322: Fundamentals of Parallel Programming

Lecture 32: Volatile variables, Java memory model

COMP 322: Fundamentals of Parallel Programming

CMSC 132: Object-Oriented Programming II

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Java s Implementation of Concurrency, and how to use it in our applications.

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

CSCD 330 Network Programming

COMP 322: Principles of Parallel Programming. Vivek Sarkar Department of Computer Science Rice University

CMSC 330: Organization of Programming Languages

CSCD 330 Network Programming

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Parallel Programming Practice

CS 159: Parallel Processing

Part IV Other Systems: I Java Threads

What is a thread anyway?

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Parallel Programming Practice

Lecture 16: Thread Safety in Java

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Synchronization SPL/2010 SPL/20 1

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

1 Shyam sir JAVA Notes

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

7. MULTITHREDED PROGRAMMING

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

CSCD 330 Network Programming

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

CSCD 330 Network Programming

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CS11 Java. Fall Lecture 7

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

CMSC 330: Organization of Programming Languages

Multithreaded Programming

Advanced Programming Concurrency

Threads and Java Memory Model

Lecture 17: Sharing Objects in Java

Unit III Rupali Sherekar 2017

CSCD 330 Network Programming

Charlie Garrod Michael Hilton

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Virtual Machine Design

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

G52CON: Concepts of Concurrency

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Concurrent Programming using Threads

Performance Throughput Utilization of system resources

MVP1: Introduction to concurrency in JAVA

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Synchronization in Java

Ch 9: Control flow. Sequencers. Jumps. Jumps

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Threads Chate Patanothai

Concurrency Utilities: JSR-166

Programming in Parallel COMP755

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Multi-threading in Java. Jeff HUANG

Java Threads. COMP 585 Noteset #2 1

Unit Testing in Java with an Emphasis on Concurrency Corky Cartwright Rice and Halmstad Universities Summer 2013

Reintroduction to Concurrency

Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Synchronization synchronization.

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Java Threads and intrinsic locks

Threads Questions Important Questions

The Java Memory Model

Animation Part 2: MoveableShape interface & Multithreading

CONCURRENT API AND PARALLEL PROGRAMMING

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Threads Synchronization

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Multiple Inheritance. Computer object can be viewed as

The New Java Technology Memory Model

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

GlobalLogic Technical Question Paper

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Charlie Garrod Bogdan Vasilescu

Tutorial 8 Date: 15/04/2014

Object Oriented Programming (II-Year CSE II-Sem-R09)

Synchronization

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Transcription:

COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 28: Java Threads (contd), synchronized statement Vivek Sarkar Department of Computer Science Rice University vsarkar@rice.edu COMP 322 Lecture 28 30 March 2011

Acknowledgments for Todayʼs Lecture" Handout for Lectures 27 and 28 Introduction to Concurrent Programming in Java, Joe Bowbeer, David Holmes, OOPSLA 2007 tutorial slides Contributing authors: Doug Lea, Brian Goetz 2

Example of creating Java threads by subclassing Thread (not recommended for wide use)" This program uses two threads: the main thread and a HelloThread Each prints a greeting the order of which is nondeterministic public static void main(string[] args) { class HelloThread extends Thread { public void run() { System.out.println( Hello from thread + Thread.currentThread().getName()); Thread t = new HelloThread(); // create HelloThread t.start(); // start HelloThread System.out.println( Hello from main thread ); Program execution ends when both user threads have completed 3

Example of creating Java threads with Runnable objects (recap)" 4

Another Example: Sequential Web Server" public class SequentialWebServer { public static final int PORT = 8080; public static void main(string[] args) throws IOException { ServerSocket server = new ServerSocket(PORT); while (true) { Socket sock = server.accept(); // get next connection try { processrequest(sock); // do the real work catch (IOException ex) { System.err.println("An error occurred..."); ex.printstacktrace(); //... rest of class definition 5

Parallelization of Web Server Example using Runnable Tasks" public class ThreadPerTaskWebServer {... public static void main(string[] args) throws IOException { ServerSocket server = new ServerSocket(PORT); while (true) { final Socket sock = server.accept(); Runnable r = new Runnable() { // anonymous implementation ; public void run() { try { processrequest(sock); catch (IOException ex) { System.err.println("An error occurred..."); new Thread(r).start();... 6

Callable Objects can be used to create Future Tasks in Java" Any class that implements java.lang.callable<v> must provide a call() method with return type V Sequential example with Callable interface 7

4 steps to create future tasks using Callable objects" 1.Create a parameter-less callable closure using a statement like Callable<Object> c = new Callable<Object>() {public Object call() { return...; ; 2.Encapsulate the closure as a task using a statement like FutureTask<Object> ft = new FutureTask<Object>(c); 3.Start executing the task in a new thread by issuing the statement, new Thread(ft).start(); 4.Wait for the task to complete, and get its result by issuing the statement, Object o = ft.get();. 8

Listings 7 and 8: parallelization of HTML renderer example" 9

Possible states for a Java thread (java.lang.thread.state)" NEW A thread that has not yet started is in this state. RUNNABLE A thread executing in the Java virtual machine is in this state. BLOCKED A thread that is blocked waiting for a monitor lock is in this state. WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state e.g., join() TIMED_WAITING A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state e.g., join() with timeout TERMINATED A thread that has exited is in this state. 10

Thread Lifecycle" A thread is created by instantiating a Thread object A thread is started by calling Thread.start() on that object Causes execution of its run() method in a new thread of execution A thread s state can be inspected by calling Thread.getState() A thread terminates by: Returning normally from its run() method Throwing an exception that isn't caught by any catch block The VM being shut down The JVM shuts down when all user (non-daemon) threads terminate Or when shutdown is requested by System.exit, CTRL/C, signal, or other process termination triggers Daemon threads are terminated when JVM shuts down Child thread inherits daemon status from parent thread Override by calling Thread.setDaemon(boolean) before starting thread Main thread is started as user thread 11

HJ isolated statement (recap from Lecture 10) " isolated <body> Two tasks executing isolated statements with interfering accesses must perform the isolated statement in mutual exclusion Two instances of isolated statements, stmt1 and stmt2, are said to interfere with each other if both access a shared location, such that at least one of the accesses is a write. Weak isolation guarantee: no mutual exclusion applies to non-isolated statements i.e., to (isolated, non-isolated) and (non-isolated, nonisolated) pairs of statement instances Isolated statements may be nested (redundant) Isolated statements must not contain any other parallel statement: async, finish, get, forall In case of exception, all updates performed by <body> before throwing the exception will be observable after exiting <body> 12

How to implement critical sections and isolated statements in Java?" Atomic variables can be used to handle special cases of isolated operations on single variable of primitive or reference type Highly recommended that you use java.util.concurrent.atomic whenever it fits your needs Need locks for more general cases. Basic idea is to implement isolated <stmt>as follows: 1. Acquire lock L i 2. Execute <stmt> 3. Release lock L i The responsibility for ensuring that the choice of locks correctly implements the semantics of isolated lies with the programmer. The main guarantee provided by locks is that only one thread can hold a lock at a time, and the thread is blocked when acquiring the lock if the lock is unavailable. 13

Objects and Locks in Java --- synchronized statements and methods" Every Java object has an associated lock acquired via: synchronized statements synchronized( foo ){ // execute code while holding foo s lock synchronized methods public synchronized void op1(){ // execute op1 while holding this lock Language does not enforce any relationship between object used for locking and objects accessed in isolated code If same object is used for locking and data access, then the object behaves like monitors Locking and unlocking are automatic Locks are released when a synchronized block exits By normal means: end of block reached, return, break When an exception is thrown and not caught 14

Example: Obvious Deadlock" This code can deadlock if lefthand() and righthand() are called concurrently from different threads 15 Because the locks are not acquired in the same order public class ObviousDeadlock {... public void lefthand() { synchronized(lock1) { synchronized(lock2) { for (int i=0; i<10000; i++) public void righthand() { synchronized(lock2) { sum += random.nextint(100); synchronized(lock1) { for (int i=0; i<10000; i++) sum += random.nextint(100);

Dynamic Order Deadlocks" There are even more subtle ways for threads to deadlock due to inconsistent lock ordering Consider a method to transfer a balance from one account to another: public class SubtleDeadlock { public void transferfunds(account from, synchronized (from) { synchronized (to) { Account to, int amount) { from.subtractfrombalance(amount); to.addtobalance(amount); What if one thread tries to transfer from A to B while another tries to transfer from B to A? Inconsistent lock order again Deadlock! 16

Avoiding Dynamic Order Deadlocks" The solution is to induce a lock ordering Here, uses an existing unique numeric key public class SafeTransfer { public void transferfunds(account from, Account to, int amount) { Account firstlock, secondlock; if (fromaccount.acctid == toaccount.acctid) throw new Exception( Cannot self-transfer ); else if (fromaccount.acctid < toaccount.acctid) { firstlock = fromaccount; secondlock = toaccount; else { firstlock = toaccount; secondlock = fromaccount; synchronized (firstlock) { synchronized (secondlock) { from.subtractfrombalance(amount); to.addtobalance(amount); 17

Java Locks are Reentrant" Locks are granted on a per-thread basis Called reentrant or recursive locks Promotes object-oriented concurrent code A synchronized block means execution of this code requires the current thread to hold this lock If it does fine If it doesn t then acquire the lock Reentrancy means that recursive methods, invocation of super methods, or local callbacks, don t deadlock public class Widget { public synchronized void dosomething() {... public class LoggingWidget extends Widget { public synchronized void dosomething() { Logger.log(this + ": calling dosomething()"); super.dosomething(); // Doesn't deadlock! 18