Basics of. Multithreading in Java

Similar documents
Concurrent Programming using Threads

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

7. MULTITHREDED PROGRAMMING

What is a thread anyway?

Introduction to Java Threads

Techniques of Java Programming: Concurrent Programming in Java

Java Threads. Introduction to Java Threads

Parallel Programming Practice

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

Parallel Programming Practice

CS 556 Distributed Systems

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

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

Advanced Concepts of Programming

Threads Questions Important Questions

EDAF65 Processes and Threads

Multithreaded Programming

EDA095 Processes and Threads

Unit - IV Multi-Threading

Java Threads. COMP 585 Noteset #2 1

CMSC 330: Organization of Programming Languages

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

Multithread Computing

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

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

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

Software Practice 1 - Multithreading

EDA095 Processes and Threads

Module - 4 Multi-Threaded Programming

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Object-Oriented Programming Concepts-15CS45

UNIT V CONCURRENT PROGRAMMING

Chapter 32 Multithreading and Parallel Programming

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.

Time-Sharing Operating Systems. EDA095 Processes and Threads. Process Creation. The Content of a Process

Model Requirements and JAVA Programs MVP 2 1

Multithreaded Programming

Object Oriented Programming. Week 10 Part 1 Threads

04-Java Multithreading

Threads Chate Patanothai

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

Chapter 19 Multithreading

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

Synchronization synchronization.

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Unit III Rupali Sherekar 2017

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

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

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

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

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

Multi-threaded programming in Java

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

Daemon thread, 7 Deadlock, 27

Only one thread can own a specific monitor

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Dr.-Ing. Michael Eichberg

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

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

Programming Language Concepts: Lecture 11

CS11 Java. Fall Lecture 7

Multi-threading in Java. Jeff HUANG

CS 351 Design of Large Programs Threads and Concurrency

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

CST242 Concurrency Page 1


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

Concurrent Programming

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

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

JAVA. Lab 12 & 13: Multithreading

Synchronized Methods of Old Versions of Java

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

Threads and Java Memory Model

Animation Part 2: MoveableShape interface & Multithreading

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 11, 2007 Objectives

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

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

Advanced Programming Methods. Lecture 7 - Concurrency in Java (2)

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it.

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

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

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

CS342: Software Design. November 21, 2017

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Multi-Threaded Concurrency in Java

Advanced Programming Concurrency

Dr.-Ing. Michael Eichberg

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

G52CON: Concepts of Concurrency

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

Problems with Concurrency. February 19, 2014

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

Programming in Java

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

Transcription:

Basics of programming 3 Multithreading in Java

Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction sequences e.g.: keyboard handling and graphical update single threaded multithreaded Basics of programming 3 BME IIT, Goldschmidt Balázs 2

Java thread basics Implicit thread handling classthread, interface Runnable representing a JVM thread threads share all memory can have static thread-specific data threads execute methods each thread executing (mostly) independently synchronization by object access (monitors) non-strict priority scheduling Basics of programming 3 BME IIT, Goldschmidt Balázs 3

java.lang.thread Object +wait() +notify() +notifyall() <<interface>> Runnable +run() Thread +id +name +priority +daemon +start() +run() +sleep() +yield() +join() Basics of programming 3 BME IIT, Goldschmidt Balázs 4

Java thread basics Entry point: run every thread must have a void run() method in this method all Java features can be used Starting a thread every thread has a void start() method it has to be called to start the thread starts a new execution thread and calls run Implementing a thread inheritance (Thread) or delegation (Runnable) Basics of programming 3 BME IIT, Goldschmidt Balázs 5

Creating and starting a thread Inheritance: extending class Thread public class MyThread extends Thread { int a; int b; public MyThread(int i) { b=i; } public void run() { for (a = 0; a < b; a++) { System.out.println(a); } } } MyThread mt = new MyThread(1000); mt.start(); MyThread mt2 = new MyThread(1500); mt2.start();... Basics of programming 3 BME IIT, Goldschmidt Balázs 6

Creating thread: inheritance Extending classthread Object +wait() +notify() +notifyall() <<interface>> Runnable +run() Thread +id +name +priority +daemon +start() +run() +sleep() +yield() +join() +run() MyThread Basics of programming 3 BME IIT, Goldschmidt Balázs 7

Creating and starting a thread Delegation: implementing if. Runnable public class MyThread implements Runnable { int a; int b; public MyThread(int i) { b=i; } public void run() { for (a = 0; a < b; a++) { System.out.println(a); } } } MyThread mt = new MyThread(1000); Thread t = new Thread(mt); // kell egy szál, ami futtat t.start();... Basics of programming 3 BME IIT, Goldschmidt Balázs 8

Creating threads: delegation Implementing interfacerunnable Object +wait() +notify() +notifyall() <<interface>> Runnable +run() -d Thread +id +name +priority +daemon +start() +run() +sleep() +yield() +join() d.run(); +run() MyThread Objektumorientált SW-tervezés BME IIT, Goldschmidt Balázs 9

java.lang.thread run() entry point of the thread (like main for an application) does not start thread! start() starts the thread, calls run() sleep(long millis [, int nanos]) thread waits for the given time Basics of programming 3 BME IIT, Goldschmidt Balázs 10

java.lang.thread interrupt() interrupts the thread when it's waiting eg. for wait, sleep, etc.interruptedexception join([long millis [,int nanos]]) waits for the given thread (for a given time) int getstate() returns state (runnable, waiting, etc, see later) boolean isalive() does is still run? Basics of programming 3 BME IIT, Goldschmidt Balázs 11

java.lang.thread int getid() returns thread id static Thread currentthread() reference to the running thread object for accessing the thread executing current code set/getname() thread s name Basics of programming 3 BME IIT, Goldschmidt Balázs 12

java.lang.thread (opt) set/getpriority() thread s priority is it daemon? setdaemon(boolean on) boolean isdaemon() sets daemon flag when JVM stops, it stops all daemon threads non-daemon threads are waited for Basics of programming 3 BME IIT, Goldschmidt Balázs 13

java.lang.thread (opt) yield() gives CPU usage to next thread ThreadGroup getthreadgroup() returns threadgroup static int activecount() number of active threads in the threadgroup Basics of programming 3 BME IIT, Goldschmidt Balázs 14

java.lang.thread Stopping a thread Thread.stop() method is deprecated volatile: details later private volatile boolean stopsignal; MyThread(){ stopsignal = false; } public void stop() { stopsignal = true; } public void run() { while (!stopsignal) { do a step or two... } } Basics of programming 3 BME IIT, Goldschmidt Balázs 15

Theads vs. Objects Objects have state (attributes, associations) behaviour (methods) Threads do execute statements described in methods have Thread objects referring to them c.f. Thread.currentThread() OO API for thread handling Basics of programming 3 BME IIT, Goldschmidt Balázs 16

Mutual exclusion Motivation some resources should be accessed by just a single thread at a time Every object has its own monitor only one thread allowed inside the monitor other threads must wait in the monitor queue recursive entry is allowed static boolean holdslock(object obj) checks if actual thread is inside monitor of obj Basics of programming 3 BME IIT, Goldschmidt Balázs 17

Mutual exclusion: monitor Object +wait() +notify() +notifyall() 1 1 Monitor * -blocked_queue 0..1 * Thread 0..1 -inside Thread Basics of programming 3 BME IIT, Goldschmidt Balázs 18

Objects' monitors explained Entering thread Monitor Thread inside Object attributes methods Blocked queue No thread in monitor Basics of programming 3 BME IIT, Goldschmidt Balázs 19

Objects' monitors explained Entering thread Monitor Thread inside Object attributes methods Blocked queue Other thread in monitor Basics of programming 3 BME IIT, Goldschmidt Balázs 20

Objects' monitors explained Entering thread Monitor Thread inside Object attributes methods Blocked queue Other thread in monitor Basics of programming 3 BME IIT, Goldschmidt Balázs 21

Objects' monitors explained Monitor Thread inside Object attributes methods Blocked queue Thread leaves monitor, next enters Basics of programming 3 BME IIT, Goldschmidt Balázs 22

Objects' monitors explained Monitor Thread inside 2 Object attributes methods 1 Blocked queue Thread leaves monitor, next enters Basics of programming 3 BME IIT, Goldschmidt Balázs 23

Mutual exclusion Monitor boundary: synchronized Hashtable<String, Integer> ht =...; public void increment(string s) {... synchronized (ht) { int i = ht.get(s); i++; ht.put(s,i); }... } Basics of programming 3 BME IIT, Goldschmidt Balázs 24

Mutual exclusion synchronized with a block needs an object reference parameter the parameter specifies the monitor to use in front of a method declaration monitor is that of the object whose method is called equivalent to a method wide synchronized block void foo() { synchronized(this) {... } } synchronized void foo() { }... Basics of programming 3 BME IIT, Goldschmidt Balázs 25

Mutual exclusion synchronized and monitors each object has its single monitor monitor can be entered from different synchronized blocks/methods only a single thread allowed in the monitor! void foo() { synchronized(x) {... } } // in object x synchronized void bar() {... } // in object x synchronized void baz() {... } Basics of programming 3 BME IIT, Goldschmidt Balázs 26

Inter-thread communication Monitors allow threads to share resources no interference Shared memory and resources allow threads to exchange data Signalling allows threads to notify each other e.g. about resource availability Basics of programming 3 BME IIT, Goldschmidt Balázs 27

Thread signalling Object.wait([long millis [,int nanos]]) if called, the thread will wait for signals for the specified time thread must be inside the monitor of the object during wait it leaves the monitor temporarily synchronized (obj) {... try { obj.wait(); // temporarily leaving monitor } catch (InterruptedException ie) {...}... } Basics of programming 3 BME IIT, Goldschmidt Balázs 28

Thread signalling Object.notify() notifies a thread that waits on the object thread must be inside the monitor of the object notified thread enters the monitor queue of the object entering monitor is handled by the monitor Object.notifyAll() same as above, but notifies all waiting threads synchronized (obj) { obj.notify(); // wakes a waiting thread } Basics of programming 3 BME IIT, Goldschmidt Balázs 29

Threads' notification explained 1. thread calls wait() on object 2. other thread enters monitor 3. other thread calls notify() on object 4. other thread leaves monitor 5. a blocked thread enters Monitor Object attributes methods Blocked queue Waiting queue Basics of programming 3 BME IIT, Goldschmidt Balázs 30

Threads' notification explained 1. thread calls wait() on object 2. other thread enters monitor 3. other thread calls notify() on object 4. other thread leaves monitor 5. a blocked thread enters Monitor 4 2 5 1a 3a 1b Object attributes methods 3b 3c Blocked queue Waiting queue Basics of programming 3 BME IIT, Goldschmidt Balázs 31

Monitors and wait-notify 1 : start RUNN ABLE WAIT ING BLOC KED T1 Obj T2 1.1: run() 2: start 1.1.1: enter 2.1: run() 2.1.1: enter 1.1.2: foo() 1.1.3: wait() 1.1.3.1: exit (2.1.1: enter) 2.1.2: notify() 2.1.2.1: enter 2.1.3: exit (1.1.3: wait) RUNN ABLE BLOCK KED RUNN ABLE 1.1.4: exit Basics of programming 3 BME IIT, Goldschmidt Balázs inside monitor state of thread 32

States of the threads NEW newly created, not yet started RUNNABLE (+running) runs or is able to run (already started) BLOCKED waits for a monitor WAITING, TIMED_WAITING waiting thread (Object.wait, Thread.sleep) TERMINATED stopped, can not be restarted Basics of programming 3 BME IIT, Goldschmidt Balázs 33

Thread state diagram (assume no exception occurs) NEW exit_mon_queue BLOCKED o.notify[all] [wait timeout] start enter _mon_queue queued RUNNABLE schedule schedule yield running o.wait o.wait(t) sleep(t) WAITING WAITING TIMED_WAITING [end_of_run] [sleep timeout] TERMINATED Basics of programming 3 BME IIT, Goldschmidt Balázs 34

Thread-safe collections Wrapper classes Fabricated by class Collections public static <T> Collection<T> synchronizedcollection(collection<t> c) also for List, Set, SortedSet, Map, SortedMap Backed by original collection Stands between client (caller) and collection Underlying collection is modified, accessed, etc Makes calls synchronized Basics of programming 3 BME IIT, Goldschmidt Balázs 35

Thread-safe collections Genuine thread-safe collection In package java.util.concurrent ConcurrentHashMap Thread-safe Map implementation CopyOnWriteArrayList/Set Modification creates new array modification are costly Iterators are independent, but can not modify Basics of programming 3 BME IIT, Goldschmidt Balázs 36

Volatile Thread data is cached Cache might be out-of-date Update e.g. before/after synch block attributes might differ in different caches Keyword volatile makes attributes s access atomic, synchronized Useful for 2-word types as well (eg. double, long) Makes data fetch atomic Basics of programming 3 BME IIT, Goldschmidt Balázs 37

Further thread features Interruption InterruptedException, etc Per-thread data ThreadLocal<T> Threadpools Callable and ExecutorService Timed starts TimerTask Basics of programming 3 BME IIT, Goldschmidt Balázs 38