concurrent programming in java - universitetet i oslo · threads in java since java does not permit...

33
Concurrent programming in Java INF4140 04.10.12 Lecture 5 0 Book: Andrews - ch.05 (5.4) Book: Magee & Kramer ch.04 - ch.07 INF4140 (04.10.12) Concurrent programming in Java Lecture 5 1 / 33

Upload: leanh

Post on 06-Sep-2018

259 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Concurrent programming in Java

INF4140

04.10.12

Lecture 5

0Book: Andrews - ch.05 (5.4)Book: Magee & Kramer ch.04 - ch.07

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 1 / 33

Page 2: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Outline

1 Monitors: review

2 Threads in Java:Thread classRunnable interface

3 Example: Interference and Java threads

4 Synchronized blocks and methods: (atomic regions and monitors)

5 Example: No interference and Java threads

6 Example:The ornamental garden

7 Condition synchronization (wait and signal)

8 Example: Mutual exclusion

9 Example: Readers/writers

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 2 / 33

Page 3: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Summary of the Last Lecture

A monitor encapsulates data, which can only be observed andmodified by the monitor’s procedures.

Contains variables that describe the stateVariables can be changed only through the available procedures

Implicit mutex: Only a procedure may be active at a time.

Two procedures in the same monitor are never executed concurrently

Condition synchronization (block a process until a particular condition holds)is given by condition variables.

Signaling disciplines:

Signal and Wait (SW): the signaller waits, and the signalled processgets to execute immediatelySignal and Continue (SC): the signaller continues, and the signalledprocess executes later

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 3 / 33

Page 4: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Java

From Wikipedia:

” ... Java is a general-purpose, concurrent, class-based,object-oriented language ...”

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 4 / 33

Page 5: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Threads in Java

A thread (processes from previous lectures) in Java has its own stack, itsown execution context and it has access to a share state.Threads may be created and deleted dynamically.

Thread

run()

MyThread

run()

The Thread class executes instructions from its methodrun(). The actual code executed depends on theimplementation provided for run() in a derived class.

c l a s s MyThread extends Thread {pub l i c vo id run ( ) {

// . . . . . .}

}// C r e a t i n g a th r ead o b j e c t :Thread a = new MyThread ( ) ;a . s t a r t ( ) ;

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 5 / 33

Page 6: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Threads in Java

Since Java does not permit multiple inheritance, we often implement therun() method in a class not derived from Thread but from the interfaceRunnable.

Runnable

run()

MyRun

run()

public interface Runnable { public abstract void run();

}

class MyRun implements Runnable { public void run() {

// ..... } }

Thread target

// C r e a t i n g a th r ead o b j e c t :Runnable b = new MyRun ( ) ;new Thread ( b ) . s t a r t ( ) ;

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 6 / 33

Page 7: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Threads in Java

To summarize:

Four steps to create a thread in Java:

1 Define a new class that extends the Java Thread class orthat implements the Runnable interface.

2 Define a run method in the new class.

3 Create an instance of the new class.

4 Start the thread.

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 7 / 33

Page 8: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Example: Interference and Java Threads

. . .c l a s s Sto r e {

p r i v a t e i n t data = 0 ;pub l i c vo id update ( ) { data++; }

}. . .

// i n a method :Sto r e s = new Sto r e ( ) ; // the t h r e ad s below have a c c e s s to st1 = new FooThread ( s ) ; t1 . s t a r t ( ) ;t2 = new FooThread ( s ) ; t2 . s t a r t ( ) ;

Threads t1 and t2 could execute s.update() concurrently!Interference between t1 and t2 ⇒ may lose updates to data.

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 8 / 33

Page 9: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Synchronized Methods

To avoid interference: Threads synchronize access to shared dataMechanism:

1 One unique lock for each object o.

2 mutex: at most one thread T can lock o at any time.

3 T makes a request to lock o in order to execute the block (statements) B asfollows:

s y n ch r on i z e d ( o ) { B}

or T makes a request to lock o in order to execute the whole method m as follows:

s y n ch r on i z e d Type m( . . . ) { . . . }

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 9 / 33

Page 10: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Example part II: No Interference

Solution to earlier problem: lock the Store objects before executingproblematic method:

c l a s s Sto r e {p r i v a t e i n t data = 0 ;

pub l i c vo id update ( ) {s y n ch r on i z e d ( t h i s ) { data++; }

}}

orc l a s s Sto r e {

p r i v a t e i n t data = 0 ;

pub l i c s y n ch r on i z e d vo id update ( ) { data++; }}. . .

// i n s i d e a method :Sto r e s = new Sto r e ( ) ;

Now only one thread at a time can run s.update().INF4140 (04.10.12) Concurrent programming in Java Lecture 5 10 / 33

Page 11: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Java Examples

Book:Concurrency: State Models &Java Programs, 2nd Edition

Jeff Magee & Jeff Kramer

Wiley

Examples in Java:http://www.doc.ic.ac.uk/~jnm/book/

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 11 / 33

Page 12: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Problem

People enter an ornamental garden through either of two turnstiles.

Management wants to know how many people are in the garden atany time.

The concurrent program consists of:

Two concurrent threads

Shared counter object

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 12 / 33

Page 13: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Problem: Class Diagram

The Turnstile thread simulates the periodic arrival of a visitor to thegarden every second by sleeping for a second and then invoking theincrement() method of the counter object.

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 13 / 33

Page 14: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Problem

c l a s s Counter {

i n t v a l u e = 0 ;NumberCanvas d i s p l a y ;

Counter ( NumberCanvas n ) {d i s p l a y . s e t v a l u e ( v a l u e ) ;}

vo id i n c r ement ( ) {i n t temp = va l u e ; // read [ v ]S imu la t e . HWinterrupt ( ) ;v a l u e = temp + 1 ; // w r i t e [ v+1]

d i s p l a y . s e t v a l u e ( v a l u e ) ;}

d i s p l a y = n ;}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 14 / 33

Page 15: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Problem

c l a s s Tu r n s t i l e extends Thread {NumberCanvas d i s p l a y ; // i n t e r f a c eCounter peop l e ; // sha r e data

Tu r n s t i l e ( NumberCanvas n , Counter c ) { // c o n s t r u c t o rd i s p l a y = n ;peop l e = c ;

}

pub l i c vo id run ( ) {t r y {

d i s p l a y . s e t v a l u e ( 0 ) ;f o r ( i n t i = 1 ; i <= Garden .MAX; i++) {

Thread . s l e e p ( 5 0 0 ) ; // 0 .5 secondd i s p l a y . s e t v a l u e ( i ) ;p eop l e . i n c r ement ( ) ; // inc r ement the coun t e r

}} catch ( I n t e r r u p t e dE x c e p t i o n e ) { }

}}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 15 / 33

Page 16: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Program

The Counter object and Turnstile threads are created by the go() methodof the Garden applet:

p r i v a t e vo id go ( ) {coun t e r = new Counter ( counterD ) ;west = new Tu r n s t i l e ( westD , coun t e r ) ;e a s t = new Tu r n s t i l e ( eastD , coun t e r ) ;west . s t a r t ( ) ;e a s t . s t a r t ( ) ;

}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 16 / 33

Page 17: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Ornamental Garden Program: DEMO

DEMO

After the East and West turnstile threads have each incremented itscounter 20 times, the garden people counter is not the sum of the countsdisplayed. Counter increments have been lost. Why?

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 17 / 33

Page 18: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Mutual Exclusion: The Ornamental Garden

c l a s s Synch ron i z edCounte r extends Counter {

Synch ron i z edCounte r ( NumberCanvas n ) {super ( n ) ;

}

s y n ch r on i z e d vo id i n c r ement ( ) {super . i n c r ement ( ) ;

}}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 18 / 33

Page 19: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Mutual Exclusion: The Ornamental Garden - DEMO

DEMO

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 19 / 33

Page 20: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Condition Synchronization (Monitors)

The following statements are defined for an arbitrary Java object oand must be executed within synchronized portions of code:

o.wait(): release lock on o, enter o’s wait queue and waito.notify(): wake up one thread in o’s wait queueo.notifyAll(): wake up all threads in o’s wait queue

There is only one (implicit) condition variable per object (waitqueue). Objects that wait on o (o.wait()) are in this implicit queue.

The ordering of the wait queue is implementation-dependent(usually FIFO).

Signaling Discipline: Signal and Continue

An awakened thread has no advantage in the competitionfor the lock to o.

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 20 / 33

Page 21: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

A Semaphore Implementation in Java

// up ( ) i s the V op e r a t i o n// down ( ) i s the P op e r a t i o n

pub l i c c l a s s Semaphore {p r i v a t e i n t v a l u e ;

pub l i c Semaphore ( i n t i n i t i a l ) {v a l u e = i n i t i a l ;

}

s y n ch r on i z e d pub l i c vo id up ( ) {++va l u e ;n o t i f y A l l ( ) ; }

s y n ch r on i z e d pub l i c vo id down ( ) throws I n t e r r u p t e dE x c e p t i o n {wh i l e ( v a l u e==0) wa i t ( ) ;− −v a l u e ;}

}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 21 / 33

Page 22: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Mutual Exclusion with Sempahores

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 22 / 33

Page 23: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Mutual Exclusion with Sempahores

c l a s s MutexLoop implements Runnable {

Semaphore mutex ;

MutexLoop ( Semaphore sema ) {mutex=sema ;}

pub l i c vo id run ( ) {t r y {

wh i l e ( t rue ) {wh i l e ( ! ThreadPane l . r o t a t e ( ) ) ;// get mutual e x c l u s i o nmutex . down ( ) ;wh i l e ( ThreadPane l . r o t a t e ( ) ) ; // c r i t i c a l s e c t i o n// r e l e a s e mutual e x c l u s i o nmutex . up ( ) ;

}} catch ( I n t e r r u p t e dE x c e p t i o n e ){}

}}

DEMO

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 23 / 33

Page 24: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

A shared database is accessed by two kinds of processes. Readers executetransactions that examine the database while Writers both examine andupdate the database. A Writer must have exclusive access to thedatabase; any number of Readers may concurrently access it.

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 24 / 33

Page 25: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s Reader implements Runnable {

ReadWrite mon i t o r ;

Reader ( ReadWrite mon i to r ) {mon i to r = moni to r ;}

pub l i c vo id run ( ) {t r y {

wh i l e ( t rue ) {wh i l e ( ! ThreadPane l . r o t a t e ( ) ) ;// beg in c r i t i c a l s e c t i o nmon i to r . acqu i r eRead ( ) ;wh i l e ( ThreadPane l . r o t a t e ( ) ) ;mon i t o r . r e l e a s eRead ( ) ;

}} catch ( I n t e r r u p t e dE x c e p t i o n e ){}

}}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 25 / 33

Page 26: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s Wr i t e r implements Runnable {

ReadWrite mon i t o r ;

Wr i t e r ( ReadWrite mon i to r ) {mon i to r = moni to r ;

}

pub l i c vo id run ( ) {t r y {

wh i l e ( t rue ) {wh i l e ( ! ThreadPane l . r o t a t e ( ) ) ;// beg in c r i t i c a l s e c t i o nmon i to r . a c qu i r eWr i t e ( ) ;wh i l e ( ThreadPane l . r o t a t e ( ) ) ;mon i t o r . r e l e a s eW r i t e ( ) ;

}} catch ( I n t e r r u p t e dE x c e p t i o n e ){}

}}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 26 / 33

Page 27: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

i n t e r f a c e ReadWrite {

pub l i c vo id acqu i r eRead ( ) throws I n t e r r u p t e dE x c e p t i o n ;

pub l i c vo id r e l e a s eRead ( ) ;

pub l i c vo id a cqu i r eWr i t e ( ) throws I n t e r r u p t e dE x c e p t i o n ;

pub l i c vo id r e l e a s eW r i t e ( ) ;}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 27 / 33

Page 28: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s ReadWri teSafe implements ReadWrite {p r i v a t e i n t r e a d e r s =0;p r i v a t e boolean w r i t i n g = f a l s e ;

pub l i c s ynch ron i zed vo id acqu i r eRead ( )throws I n t e r r u p t e dE x c e p t i o n {

wh i l e ( w r i t i n g ) wa i t ( ) ;++r e a d e r s ;

}

pub l i c s ynch ron i zed vo id r e l e a s eRead ( ) {− −r e a d e r s ;i f ( r e a d e r s==0) n o t i f y A l l ( ) ;

}

pub l i c s ynch ron i zed vo id a cqu i r eWr i t e ( ) { . . . }

pub l i c s ynch ron i zed vo id r e l e a s eW r i t e ( ) { . . . }}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 28 / 33

Page 29: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s ReadWri teSafe implements ReadWrite {p r i v a t e i n t r e a d e r s =0;p r i v a t e boolean w r i t i n g = f a l s e ;

pub l i c s ynch ron i zed vo id acqu i r eRead ( ) { . . . }

pub l i c s ynch ron i zed vo id r e l e a s eRead ( ) { . . . }

pub l i c s ynch ron i zed vo id a cqu i r eWr i t e ( )throws I n t e r r u p t e dE x c e p t i o n {

wh i l e ( r e ad e r s >0 | | w r i t i n g ) wa i t ( ) ;w r i t i n g = t rue ;

}

pub l i c s ynch ron i zed vo id r e l e a s eW r i t e ( ) {w r i t i n g = f a l s e ;n o t i f y A l l ( ) ;

}}

DEMO

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 29 / 33

Page 30: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem - Fairness

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 30 / 33

Page 31: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s ReadWr i t eFa i r implements ReadWrite {

p r i v a t e i n t r e a d e r s =0;p r i v a t e boolean w r i t i n g = f a l s e ;p r i v a t e i n t waitingW = 0 ; // no o f wa i t i n g Wr i t e r s .p r i v a t e boolean r e a d e r s t u r n = f a l s e ;

s ynch ron i zed pub l i c vo id acqu i r eRead ( )throws I n t e r r u p t e dE x c e p t i o n {

wh i l e ( w r i t i n g | | ( waitingW>0 && ! r e a d e r s t u r n ) ) wa i t ( ) ;++r e a d e r s ;

}

s ynch ron i zed pub l i c vo id r e l e a s eRead ( ) {− −r e a d e r s ;r e a d e r s t u r n=f a l s e ;i f ( r e a d e r s==0) n o t i f y A l l ( ) ;

}

s ynch ron i zed pub l i c vo id a cqu i r eWr i t e ( ) { . . . }s ynch ron i zed pub l i c vo id r e l e a s eW r i t e ( ) { . . . }

}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 31 / 33

Page 32: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

c l a s s ReadWr i t eFa i r implements ReadWrite {

p r i v a t e i n t r e a d e r s =0;p r i v a t e boolean w r i t i n g = f a l s e ;p r i v a t e i n t waitingW = 0 ; // no o f wa i t i n g Wr i t e r s .p r i v a t e boolean r e a d e r s t u r n = f a l s e ;

s ynch ron i zed pub l i c vo id acqu i r eRead ( ) { . . . }s ynch ron i zed pub l i c vo id r e l e a s eRead ( ) { . . . }

s ynch ron i zed pub l i c vo id a cqu i r eWr i t e ( )throws I n t e r r u p t e dE x c e p t i o n {

++waitingW ;wh i l e ( r e ade r s >0 | | w r i t i n g ) wa i t ( ) ;−−waitingW ; w r i t i n g = t rue ;

}

s ynch ron i zed pub l i c vo id r e l e a s eW r i t e ( ) {w r i t i n g = f a l s e ; r e a d e r s t u r n=t rue ;n o t i f y A l l ( ) ;

}}

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 32 / 33

Page 33: Concurrent programming in Java - Universitetet i Oslo · Threads in Java Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived

Readers and Writers problem

DEMO

INF4140 (04.10.12) Concurrent programming in Java Lecture 5 33 / 33