Overview of Java Threads (Part 2)

Similar documents
Benefits of Concurrency in Java & Android: Program Structure

Overview of Java Threads (Part 3)

Object Oriented Programming. Week 10 Part 1 Threads

Infrastructure Middleware (Part 3): Android Runtime Core & Native Libraries

Java Barrier Synchronizers: CountDownLatch (Part 1)

The Java Executor (Part 1)

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

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

Threads Questions Important Questions

Java Barrier Synchronizers: CyclicBarrier (Part 1)

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CMSC 132: Object-Oriented Programming II. Threads in Java

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

The Java FutureTask. Douglas C. Schmidt

Infrastructure Middleware (Part 1): Hardware Abstraction Layer (HAL)

Java ReentrantLock (Part 1)

Unit - IV Multi-Threading

The Java ExecutorService (Part 1)

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Java Threads. Written by John Bell for CS 342, Spring 2018

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Java Semaphore (Part 1)

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

Java 8 Parallel ImageStreamGang Example (Part 3)

What is a thread anyway?

Overview of Java s Support for Polymorphism


7. MULTITHREDED PROGRAMMING

Overview of Activities

public class Shared0 { private static int x = 0, y = 0;

CS 351 Design of Large Programs Threads and Concurrency

Concurrent Programming using Threads

G52CON: Concepts of Concurrency

Overview of Layered Architectures

Java Monitor Objects: Synchronization (Part 1)

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

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

Overview of Advanced Java 8 CompletableFuture Features (Part 3)

Java Threads. COMP 585 Noteset #2 1

Unit III Rupali Sherekar 2017

By: Abhishek Khare (SVIM - INDORE M.P)

Figure 6.1 System layers

External vs. Internal Iteration in Java 8

Introduction to Java Threads

Chapter 3 Process Description and Control

Synchronized Methods of Old Versions of Java

CMSC 330: Organization of Programming Languages

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

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

Java 8 Parallel Stream Internals (Part 2)

Multithreading using Java. Dr. Ferdin Joe John Joseph

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Threads in Java (Deitel & Deitel)

Dining philosophers (cont)

Threads Chate Patanothai

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

EDAF65 Processes and Threads

EDA095 Processes and Threads

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Multi-threading in Java. Jeff HUANG

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

CIS233J Java Programming II. Threads

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

Project Loom Ron Pressler, Alan Bateman June 2018

Concurrent Computing CSCI 201 Principles of Software Development

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

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

Multithreaded Programming

Multithread Computing

Threads & Concurrency

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

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

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

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

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

Model Requirements and JAVA Programs MVP 2 1

Module - 4 Multi-Threaded Programming

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

UNIT V CONCURRENT PROGRAMMING

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

Overview of Java 8 Parallel Streams (Part 1)

Basics of. Multithreading in Java

Techniques of Java Programming: Concurrent Programming in Java

CS180 Review. Recitation Week 15

JAVA. Lab 12 & 13: Multithreading

Chapter 19 Multithreading

Contents. 6-1 Copyright (c) N. Afshartous

Software Practice 1 - Multithreading

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Overview of Advanced Java 8 CompletableFuture Features (Part 2)

Chapter 32 Multithreading and Parallel Programming

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

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

Threads & Concurrency

THREADS & CONCURRENCY

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

Class BinarySemaphore

Transcription:

Overview of Java Threads (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA

Learning Objectives in this Part of the Lesson Understand how Java threads support concurrency Learn how our case study app works Know alternative ways of giving code to a thread Learn how to pass parameters to a Java thread Know how to run a Java thread oncreate() : My Component new() : MyThread start() run() 2

Learning Objectives in this Part of the Lesson Understand how Java threads support concurrency Learn how our case study app works Know alternative ways of giving code to a thread Learn how to pass parameters to a Java thread Know how to run a Java thread Recognize common thread methods 3

Learning Objectives in this Part of the Lesson Understand how Java threads support concurrency Learn how our case study app works Know alternative ways of giving code to a thread Learn how to pass parameters to a Java thread Know how to run a Java thread Recognize common thread methods Appreciate Java thread happens-before orderings 4

Running Java Threads 5

There are multiple layers involved in creating & starting a thread Running Java Threads : My Component : MyThread oncreate() new() start() run() Threading & Synchronization Packages Java Virtual Machine System Libraries Operating System Kernel See Part 2 of the upcoming lesson on Managing the Java 6 Thread Lifecycle

There are multiple layers involved in creating & starting a thread A new thread object doesn t allocate a run-time call stack of activation records Running Java Threads oncreate() : My Component new() : MyThread See en.wikipedia.org/ wiki/call_stack 7

There are multiple layers involved in creating & starting a thread A new thread object doesn t allocate a run-time call stack of activation records The runtime stack & other thread resources are only allocated after the start() method is called Running Java Threads oncreate() : My Component new() start() : MyThread run() 8

There are multiple layers involved in creating & starting a thread A new thread object doesn t allocate a run-time call stack of activation records The runtime stack & other thread resources are only allocated after the start() method is called Running Java Threads The JVM invokes a thread s run() hook method after start() creates its resources oncreate() : My Component new() start() : MyThread run() 9

There are multiple layers involved in creating & starting a thread A new thread object doesn t allocate a run-time call stack of activation records Running Java Threads The runtime stack & other thread resources are only allocated after the start() method is called The JVM invokes a thread s run() hook method after start() creates its resources Each thread can run concurrently & block independently oncreate() : My Component new() start() : MyThread run() 10

Running Java Threads Any code can generally run in a thread : My Component : MyThread oncreate() new() start() run() public void run(){ } // code to run goes here 11

Any code can generally run in a thread However, windowing toolkits often restrict which thread can access GUI components Running Java Threads oncreate() : My Component new() : MyThread start() run() 12

Any code can generally run in a thread However, windowing toolkits often restrict which thread can access GUI components e.g., only the Android UI thread can access GUI components Running Java Threads oncreate() : My Component new() start() : MyThread run() See developer.android.com/training/ 13 multiple-threads/communicate-ui.html

Running Java Threads A thread can live as long as its run() hook method hasn t returned : My Component : MyThread oncreate() new() start() run() 14

Running Java Threads A thread can live as long as its run() hook method hasn t returned The OS scheduler can suspend & resume a thread many times during its lifecycle oncreate() : My Component new() : MyThread start() run() 15

Running Java Threads A thread can live as long as its run() hook method hasn t returned The underlying thread scheduler can suspend & resume a thread many times during its lifecycle oncreate() : My Component new() : MyThread start() run() These scheduler operations are largely transparent to user code, as long as synchronization 16 is performed properly..

Running Java Threads For a thread to execute forever, its run() hook method needs an infinite loop : My Component : MyThread oncreate() new() start() run() public void run(){ } while (true) {... } 17

The thread is dead after run() returns Running Java Threads : My Component : MyThread oncreate() new() start() run() 18

The thread is dead after run() returns A thread can end normally Running Java Threads : My Component : MyThread oncreate() new() public void run(){ } while (true) {... return; } start() run() 19

The thread is dead after run() returns A thread can end normally Or an uncaught exception can be thrown Running Java Threads oncreate() : My Component new() : MyThread public void run(){ while (true) {... throw new SomeException(); } } start() run() 20

Running Java Threads The join() method allows one thread to wait for another thread to complete : My Component : MyThread oncreate() new() start() run() join() 21

Running Java Threads The join() method allows one thread to wait for another thread to complete : My Component : MyThread oncreate() new() start() run() join() Simple form of barrier synchronization See upcoming lessons on 22 Java Barrier Synchronizers

Running Java Threads The join() method allows one thread to wait for another thread to complete Or a thread can simply evaporate! oncreate() : My Component 23

Running Java Threads The join() method allows one thread to wait for another thread to complete Or a thread can simply evaporate! The JVM recycles the resources associated with the thread oncreate() : My Component 24

Running Java Threads The join() method allows one thread to wait for another thread to complete Or a thread can simply evaporate! The JVM recycles the resources associated with the thread e.g., runtime stack of activation records, thread-specific storage, etc. oncreate() : My Component 25

Some Common Java Thread Methods 26

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class See docs.oracle.com/javase/7/ docs/api/java/lang/thread.html 27

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() Marks thread as a daemon See javarevisited.blogspot.com/2012/03/ what-is-daemon-thread-in-java-and.html 28

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() Allocates thread resources & initiates thread execution 29

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() Hook method where user code is supplied See wiki.c2.com/?hookmethod 30

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() Waits for a thread to finish A simple form of barrier 31 synchronization

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Sleeps for given time in ms 32

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Thread currentthread() Object for current Thread 33

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Thread currentthread() void interrupt() Post an interrupt request to a Thread See part 3 of upcoming lesson on Managing the Java 34 Thread Lifecycle

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Thread currentthread() void interrupt() boolean isinterrupted() Tests whether a thread has been interrupted isinterrupted() can be called multiple times w/out affecting the 35 interrupted status

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Thread currentthread() void interrupt() boolean isinterrupted() boolean interrupted() Tests whether current thread has been interrupted interrupted() clears the interrupted status the first 36 time it s called

Some Common Java Thread Methods There are a number of commonly used methods in the Java Thread class, e.g., void setdaemon() void start() void run() void join() void sleep(long time) Thread currentthread() void interrupt() boolean isinterrupted() boolean interrupted() void setpriority(int newpriority) & int getpriority() Set & get the priority of a Thread 37

Java Thread Happens- Before Orderings 38

Java Thread Happens-Before Orderings Java Threads methods establish happens-before orderings See en.wikipedia.org/ wiki/happened-before 39

Java Thread Happens-Before Orderings Java Threads methods establish happens-before orderings Ensure that if one event happens before another event, the result must reflect that, even if those events are actually executed out of order See en.wikipedia.org/ wiki/happened-before 40

Java Thread Happens-Before Orderings Java Threads methods establish happens-before orderings Ensure that if one event happens before another event, the result must reflect that, even if those events are actually executed out of order e.g., to optimize program flow & concurrency 41

Java Thread Happens-Before Orderings Java Threads methods establish happens-before orderings Ensure that if one event happens before another event, the result must reflect that, even if those events are actually executed out of order In general, a happens-before relationship guarantees that memory written to by statement A is visible to statement B i.e., statement A completes its write to ready before statement B starts its read 42

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java See en.wikipedia.org/wiki/ Java_memory_model 43

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); 44

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called, e.g. Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); This lambda plays the role of the run() hook method! 45

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called, e.g. Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); A thread s state is consistent & visible before run() starts 46

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Methods in java.util.concurrent package classes also establish happen-before orderings See docs.oracle.com/javase/8/docs/api/java/ util/concurrent/package-summary.html 47

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Methods in java.util.concurrent package classes also establish happen-before orderings, e.g. // Thread t1 ConcurrentMap concurrentmap = new ConcurrentHashMap(); concurrentmap.put("key", "value"); // Thread t2 Object value = concurrentmap.get("key"); Placing an object into a concurrent collection happens-before the access or removal of the element from the collection 48

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Methods in java.util.concurrent package classes also establish happen-before orderings The termination of a thread happens-before a join() with the terminated thread Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); t1.join(); 49

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Methods in java.util.concurrent package classes also establish happen-before orderings The termination of a thread happens-before a join() with the terminated thread, e.g. Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); t1.join(); This thread terminates after its lambda expression runnable completes 50

Java Thread Happens-Before Orderings Examples of happens-before relationships in Java Starting a thread happens-before the run() hook method of the thread is called Methods in java.util.concurrent package classes also establish happen-before orderings The termination of a thread happens-before a join() with the terminated thread, e.g. Thread t1 = new Thread(() -> System.out.println ("hello world")).start(); t1.join(); A thread waiting on a (non-timed) join() only resumes after the target thread terminates 51

End of Overview of Java Threads (Part 2) 52