Java - Concurrent programming - Thread's basics

24
CONCURRENT PROGRAMMING THREAD’S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 – 2016 [email protected]

Transcript of Java - Concurrent programming - Thread's basics

Page 1: Java - Concurrent programming - Thread's basics

CONCURRENT PROGRAMMINGTHREAD’S BASICSPROGRAMMAZIONE CONCORRENTE E DISTR.Università degli Studi di Padova

Dipartimento di Matematica

Corso di Laurea in Informatica, A.A. 2015 – [email protected]

Page 2: Java - Concurrent programming - Thread's basics

2Programmazione concorrente e distribuita

SUMMARY Introduction Thread basics

Thread properties Thread states

Thread interruption Sequence diagrams

Riccardo Cardin

Page 3: Java - Concurrent programming - Thread's basics

3Programmazione concorrente e distribuita

INTRODUCTION Multitasking

The ability to have more than a program working at what seems like the same time

The unity of this type of programming is a process A process has its own variables Communication between process is accomplished using

messages sent over a common channel (i.e. a socket) Very hard to accomplish and no so performant

Types Cooperative: CPU control is left to the processes Time-sliced: the OS (scheduler) assigns a time slice to each

process

Riccardo Cardin

Page 4: Java - Concurrent programming - Thread's basics

4Programmazione concorrente e distribuita

INTRODUCTION Multithread

A programming model that allows multiple threads to exists within the same context of a single process Every process will appear to do multiple tasks Threads share the same data and variables

Every process as a main thread This thread can create other threads, called secondary Every thread as a priority order (1 .. 10)

Types Cooperative Time-sliced: thread scheduling is left to the main thread, that

uses OS utilities

Riccardo Cardin

Page 5: Java - Concurrent programming - Thread's basics

5Programmazione concorrente e distribuita

INTRODUCTION

Riccardo Cardin

Page 6: Java - Concurrent programming - Thread's basics

6Programmazione concorrente e distribuita

INTRODUCTION

Riccardo Cardin

Process

Mem

ory

Thread 1

Task Task

Thread 2

Task

Thread 3

Task

Threads share the

same memory chunks

Every thread could be reused to execute

different tasksThreads are lighter than processes,

even so their creation is still

time-consuming

Each process can execute

many threads

Threads are a mechanism

provided by the OS

Page 7: Java - Concurrent programming - Thread's basics

7Programmazione concorrente e distribuita

DEFINITION

Multithread programmingA programming model that allows multiple threads to

exists within the same context of a single process Responsiveness Faster execution Lower resource consumption Parallelization

Java has built-in support for concurrent programming

Riccardo Cardin

A thread is the smallest sequence of programmed instructions that can be managed independently. Multiple thread can exist within the same process, executing concurrently and share resources such as memory.

- Wikipedia

Page 8: Java - Concurrent programming - Thread's basics

8Programmazione concorrente e distribuita

THREAD BASICS Threads in Java are the primitives that actually

execute tasksRunnable interface describes a task you want to

run, usually concurrently with others The code of the run method will be executed in a thread

Tasks are short lived, so you don’t waste the time to start a thread

Riccardo Cardin

public interface Runnable { void run();}

Runnable task = () -> { int i = 0; while (i < 1000) i++; }new Thread(task).start(); // A thread running a task

Page 9: Java - Concurrent programming - Thread's basics

9Programmazione concorrente e distribuita

THREAD BASICS You should decouple the task that is to be run in

parallel from the mechanism of running itYou can also define a subclass of Thread, but this

approach is no longer recommended If you have many task is to expensive create a single thread

for each one

Do not call the run method on Thread or Runnable instances The task is merely executed in the same thread Riccardo Cardin

class MyThread extends Thread { public void run() { // task code, don’t do this!!! }}

Page 10: Java - Concurrent programming - Thread's basics

10Programmazione concorrente e distribuita

THREAD BASICS

Riccardo Cardin

Page 11: Java - Concurrent programming - Thread's basics

11Programmazione concorrente e distribuita

THREAD BASICS The main method executes in the main thread

From the main thread they can be executed other thread, called secondary They execute in pararrel wrt the main thread

Threads can be of two typeUser threads

JVM stops when there are no more user thread executingDeamon threads

A deamon stops when its user thread stops

Riccardo Cardin

public class Example { public static void main(String[] args) { // This code runs inside the main thread }}

Page 12: Java - Concurrent programming - Thread's basics

12Programmazione concorrente e distribuita

THREAD PROPERTIES Thread priorities

Use setPriority method to give a thread a priority MIN_PRIORITY = 1 and MAX_PRIORITY = 10 Don’t use priorities, they are too highly system-dependent

Deamon threadsUse setDeamon method

Its only role is to serve other threads When only deamon threads remain, the JVM exits

Handlers for uncaught exceptionsThe run method cannot throw any checked ex.

Install an UncaughtExceptionHandler to manage ex.

Riccardo Cardin

Page 13: Java - Concurrent programming - Thread's basics

13Programmazione concorrente e distribuita

THREAD STATES 6 thread states

NewRunnableBlockedWaitingTime waitingTerminated

Use getState method

Thread.State

No resources associated

Runnable ≠ Running

Page 14: Java - Concurrent programming - Thread's basics

14Programmazione concorrente e distribuita

THREAD STATES New threads

Just created with the new operator. Not yet running Runnable threads

Once the start method is invoked. Resource creation, scheduling run method is invoked It may or not actually be running

DO NOT CALL RUN METHOD DIRECTLY!

Riccardo Cardin

public static void main(String[] args) { // Not concurrent, but sequential new MyThread().run(); for (int i = 0; i < 200; i++) System.out.println("Cycle - " + i);}

Page 15: Java - Concurrent programming - Thread's basics

15Programmazione concorrente e distribuita

THREAD STATES Blocked and Waiting threads

Temporarily inactive A thread becomes blocked when it tries to acquire an intrinsic

object lock When a thread waits for another thread to notify of a

condition, it enters the waiting state The calling of a timeout parameters causes the thread to

enter the timed waiting (Thread.sleep) A thread waits for another thread to finish, calling the join

method on it Terminated threads

It is not possible to reborn a thread in this state

Riccardo Cardin

Page 16: Java - Concurrent programming - Thread's basics

16Programmazione concorrente e distribuita

THREADS INTERRUPTION A thread terminates when it’s run method:

Returns by executing a return statementAfter executing the last statement in method body If an unhandled exception occurs

It is possible to send an interruption requestUse the interrupt method

Thread states becomes interrupted, but thread is not interrupted by the JVM

Thread should check whether it has been interrupted

Riccardo Cardin

while (!Thread.currentThread().isInterrupted() && more work to do) { // do more work}

Page 17: Java - Concurrent programming - Thread's basics

17Programmazione concorrente e distribuita

THREADS INTERRUPTION Waiting for another thread to finish

Use join() or join(long millis) An instance of the joining thread must be available Passing a time interval to the method has the effect to limit

the waiting period to millis milliseconds

Riccardo Cardin

Thread thread = new Thread(() -> { // Do some heavy work});thread.start();try { // Waiting for at max 1 second the termination of thread thread.join(1000L);} catch(InterruptedException e) { // thread was interrupted during sleep} finally { // cleanup, if required}

Page 18: Java - Concurrent programming - Thread's basics

18Programmazione concorrente e distribuita

THREADS INTERRUPTION Implementing collaborative preemption

Thread.yield() notifies the system that the current thread is willing to "give up the CPU" for a while. Thread scheduler will select a different thread to run

If no other thread is present, the statement has no effect

When to use yield()? Practically NEVER Use Thread.sleep() (requires some self-computation) Use synchronization mechanisms if waiting for a process or

a resourceRiccardo Cardin

while ( /* more work to do */ ) { // do more work Thread.yield();}

Page 19: Java - Concurrent programming - Thread's basics

19Programmazione concorrente e distribuita

THREADS INTERRUPTION Interrupting a thread simply grabs its attention

Use Thread.sleep(long time) to suspend temporarily the thread If the interrupted thread was sleeping or waiting for

something, an InterruptedException is thrown ...and the thread status is cleared!

Riccardo Cardin

try { while ( /* more work to do */ ) { // do more work Thread.sleep(delay); }} catch(InterruptedException e) { // thread was interrupted during sleep} finally { // cleanup, if required}

Page 20: Java - Concurrent programming - Thread's basics

20Programmazione concorrente e distribuita

THREADS INTERRUPTION

Riccardo Cardin

Page 21: Java - Concurrent programming - Thread's basics

21Programmazione concorrente e distribuita

SEQUENCE DIAGRAMS How can we reason about thread visually?

UML gives use sequence diagrams

Riccardo Cardin

Partecipant

Time passing

Life line

Page 22: Java - Concurrent programming - Thread's basics

22Programmazione concorrente e distribuita

SEQUENCE DIAGRAMS

Riccardo Cardin

A sequence diagram describes the cooperation between a group of objects that have to interact with each other to fulfill an objective

Definition

Message

Find messageInternal

call

Return

Object creation

Page 23: Java - Concurrent programming - Thread's basics

23Programmazione concorrente e distribuita

EXAMPLES

Riccardo Cardin

https://github.com/rcardin/pcd-snippets

Page 24: Java - Concurrent programming - Thread's basics

24Programmazione concorrente e distribuita

REFERENCES Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay

Horstmann, Gary Cornell, 2012, Prentice Hall Thread.yield http://

www.javamex.com/tutorials/threads/yield.shtml What are the main uses of yield(), and how does it differ from join()

and interrupt()? http://stackoverflow.com/questions/6979796/what-are-the-main-uses-of-yield-and-how-does-it-differ-from-join-and-interr

Chap. 10 «Concurrent Programming», Core Java for the Impatient, Cay Horstmann, 2015, Addison-Wesley

Riccardo Cardin