operating systems frans sanen. recap of threads in java learn to think about synchronization...

Post on 14-Jan-2016

218 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

OPERATING SYSTEMS

Frans Sanen

Recap of threads in Java Learn to think about synchronization

problems in Java Solve synchronization problems in Java

2

One of the key success factors of Java Thread = flow of control Threads can share state If a program involves multiple threads,

synchronization becomes an issue! Coordination is needed when several threads

access and manipulate shared state

3

class Animation implements Runnable {

Thread myThread;

Animation (String name) {

myThread = new Thread( this ); myThread.start();

}

public void run() {

while ( true ) {

// Draw Frames

...

repaint();

}

}

}

class Animation extends Thread {

public void run() {

while (true ) {

// Draw Frames

...

repaint();

}

}

}

Wait and notify monitor as the underlying mechanism Thread can suspend itself by calling wait() Waiting thread will be suspended if another

thread executes notify() Java also provides notifyAll() method

Methods wait(), notify() and notifyAll() only can be invoked from within monitor regions

Monitor guarantees mutual exclusion when an object is executing in a monitor region Synchronized method

public void synchronized doSth() {...}

Synchronized code blocksynchronized (this) {...}

9

Producer produces items and puts them in a shared buffer

Consumer consumes items and gets them out a shared buffer

Producer can’t produce items if the buffer is full.

Consumer can’t consume items if the buffer is empty.

10

Readers try to read (access) shared data Writers try to write (manipulate) shared

data

Only one writer can write shared data at a given moment in time (“no two writers”).

It never may be the case that both a reader and a writer are working with shared data simultaneously (“no reader and writer at the same time”).

11

Good luck!

If two or more threads modify a shared object, declare the methods / code blocks that carry out the modification as synchronized.

If a thread must wait for the state of a shared object to change, it should wait inside the object, not outside, by entering the synchronized method / code block and calling wait().

Whenever a method / code block changes the state of a shared object, it should call notify()to give waiting threads a chance to see if circumstances have changed.

Keep the synchronized granularity as low as possible to maximize parallelism.

top related