Download presentation
Presentation is loading. Please wait.
1
System Programming Practical Session 7
Synchronization, Liveness, Guarded Methods, and Thread Timing
2
Synchronization A mechanism allowing safely accessing shared resources. A thread accessing a synchronized method locks the object. The object cannot be accessed by other threads while it is locked.
3
Synchronization 1. Class Even{ 2. private long n = 0;
3. public long next(){ 4. n++; 5. n++; 6. return n; 7. } 8. }
4
Synchronization 1. Class Even{ 2. private long n = 0;
3. public synchronized long next(){ 4. n++; 5. n++; 6. return n; 7. } 8. }
5
Synchronizing a block public int foo() { // do something safe
synchronized(this) { // do something return 9; } }
6
Solution to safety problem
Printer Example (from practical session 1) class Printer { Printer() {} /** 40 times */ public synchronized void printALine(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) { System.out.print(s); } System.out.println(); } }
7
public class GoodSynchronization{
public static void main(String[] a) { Printer p = new Printer(); Thread t1 = new Thread( new SimpleAsynchronousTask("a", p) ); Thread t2 = new Thread( new SimpleAsynchronousTask("b", p) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb } } class SimpleAsynchronousTask implements Runnable { Printer m_p; String m_name; public SimpleAsynchronousTask(String name, Printer p) { m_p = p; m_name = name; } public void run() { for (int i = 0; i<50; i++) { m_p.printALine(i, m_name); } } }
8
Wrong solution #1 public class BadSynchronization2
public static void main(String[] a) { Printer p1 = new Printer(); Printer p2 = new Printer(); Thread t1 = new Thread( new SimpleAsynchronousTask("a", p1) ); Thread t2 = new Thread( new SimpleAsynchronousTask("b", p2) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb } } class SimpleAsynchronousTask implements Runnable { .....the same like GoodSynchronization.java class Printer {
9
Wrong solution #2 (no printer object)
class BadSynchronization { public static void main(String[] a) { Thread t1 = new Thread( new SimpleAsynchronousTask("a") ); Thread t2 = new Thread( new SimpleAsynchronousTask("b") ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb } } class SimpleAsynchronousTask implements Runnable { .....the same like GoodSynchronization.java public synchronized void printALine(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) System.out.print(s); System.out.println();
10
Liveness A concurrent application's ability to execute in a timely manner. Liveness problems: Deadlock Starvation Livelock
11
Deadlock Thread 2 Thread 1 acquire Scanner acquire Printer
use scanner use printer release Scanner release Printer Thread 1 acquire Printer acquire Scanner use printer use scanner release Printer release Scanner Thread 1 Thread 2
12
public class Deadlock {
public static void main(String[] args) { final Object resource1 = “Printer"; final Object resource2 = “Scanner"; Thread t1 = new Thread(new Runnable() { public void run() { synchronized(resource1) { System.out.println("Thread 1: locked resource 1"); try {Thread.sleep(50);} catch (InterruptedException e){} synchronized(resource2) { System.out.println("Thread 1: locked resource 2"); }/* release resource2 */ }/* release resource1 */ } } ); Thread t2 = new Thread(new Runnable() { synchronized(resource2) { System.out.println("Thread 2: locked resource 2"); try{Thread.sleep(50);} catch(InterruptedException e){} synchronized(resource1) { System.out.println("Thread 2: locked resource 1"); }/* release resource1 */ }/* release resource2 */ } } ); t1.start(); t2.start(); } }
13
Resource Ordering All threads acquire the locks in the same order.
acquire Printer acquire Scanner use printer use scanner release Printer release Scanner Thread 2 acquire Printer acquire Scanner use printer use scanner release Printer release Scanner
14
Starvation Some threads are waiting forever for resources that are used by other threads.
15
Starvation Some threads are waiting forever for resources that are used by other threads. Example1: A solution to the dinning philosophers problem in which philosophers 1,3,5 never eat, and philosophers 2,4 eat whenever they want. 3 2 4 1 5
16
Starvation Example 2: Threads with priority.
Each thread has a priority: Low or High. Low priority threads execute only if there are no high priority threads. High priority threads keep coming. High Low
17
Livelock Threads are unable to make progress although they are not blocked.
18
Livelock Threads are unable to make progress although they are not blocked. Example: two threads trying to pass a shared corridor. Thread protocol: if there is an obstacle, then move aside.
19
Livelock Threads are unable to make progress although they are not blocked. Example: two threads trying to pass a shared corridor. Thread protocol: if there is an obstacle, then move aside.
20
Guarded Methods The guarded method model delays the execution of a thread until a condition is satisfied. A thread that is unable to proceed, waits for condition change made by another thread.
21
Basic Thread Timing Example
Each thread is assigned a number from {1,2,…,k}. In any point in time, only threads assigned a certain number run. Other threads wait. 1 3
22
Basic Thread Timing Example
Each thread is assigned a number from {1,2,…,k}. In any point in time, only threads assigned a certain number run. Other threads wait. 1 3
23
class Checker { private int m_num; public Checker(int num) { this.m_num = num; } public synchronized void change(int num) { public synchronized boolean check(int num){ return (num == this.m_num); }
24
public class Threads01 { public static void main(String[] args) { Checker checkerObject = new Checker(0); Thread t[] = new Thread[9]; for (int i = 0; i < t.length ; i++) t[i] = new Thread(new SleepThread(i/3+1, "NO. " +(i+1)+ " done, was waiting for "+(i/3+1), checkerObject)); for (int i = 0; i < t.length; i++) t[i].start(); try { Thread.sleep(1000); checkerObject.change(1); Thread.sleep(1000); checkerObject.change(3); checkerObject.change(2); } catch (InterruptedException e) {} } }
25
Solution #1: Busy Waiting
class SleepThread implements Runnable { private int m_num; private String m_strToPrintWhenDone; private Checker m_checkerObject; SleepThread(int num, String strToPrintWhenDone, Checker checkerObject) { this.m_num = num; this.m_strToPrintWhenDone = strToPrintWhenDone; this.m_checkerObject = checkerObject; } public void run() { /* busy waiting */ while (!this.m_checkerObject.check(this.m_num)) ; System.out.println(this.m_strToPrintWhenDone); }
26
Solution #2: Sleep and Check
class SleepThread implements Runnable { private int m_num; private String m_strToPrintWhenDone; private Checker m_checkerObject; SleepThread(int num, String strToPrintWhenDone, Checker checkerObject) { this.m_num = num; this.m_strToPrintWhenDone = strToPrintWhenDone; this.m_checkerObject = checkerObject; } public void run() { while (!this.m_checkerObject.check(this.m_num)) { try { Thread.sleep(100); } catch (InterruptedException e) {} } System.out.println(this.m_strToPrintWhenDone); }
27
Solution #3: Wait and Notify
class SleepThread implements Runnable { ……… public void run() { this.m_checkerObject.returnWhenCheckIsTrue(m_num); System.out.println(m_strToPrintWhenDone); } } class Checker { private int m_num; public Checker(int num) { this.m_num = num; } public synchronized void change(int num){ this.m_num = num; this.notifyAll(); } public synchronized void returnWhenCheckIsTrue(int num) { while (num != m_num) { try { this.wait(); } catch (InterruptedException e) {} } } }
28
Tips Use a while loop (and not an if condition) to check the precondition notify() Vs. notifyAll() - which of them should you use? When calling wait(), notifyAll() or notify() on an object, make sure the calling thread holds the object's lock. Notice that if you do not hold the object's lock you will receive an illegal monitor runtime exception. After performing a wait call on the object, the thread releases the object's lock. Furthermore, before exiting the wait set of the object, the thread must re-lock the object A thread that releases an object's, lock will NOT release other locks it has
29
Advanced Synchronization Tools
CountDownLatch Constructor: CountDownLatch(int value) Methods: void countDown() Decrements the latch value by 1. void await() Causes the current thread to wait until the latch has counted down to zero.
30
import java.util.concurrent.*;
public class Threads { public static void main(String[] args) { CountDownLatch latchObject = new CountDownLatch (3); Server s = new Server (latchObject); Client c1 = new Client (1, latchObject); Client c2 = new Client (2, latchObject); Client c3 = new Client (3, latchObject); Thread t1=new Thread(s); Thread t2=new Thread(c1); Thread t3=new Thread(c2); Thread t4=new Thread(c3); t1.start(); t2.start(); t3.start(); t4.start(); } }
31
class Server implements Runnable {
private CountDownLatch m_latchObject; public Server(CountDownLatch latchObject) { m_latchObject = latchObject; } public void run () synchronized (System.out) { System.out.println("Server initialized"); } try { m_latchObject.await(); } catch (InterruptedException e) return; } System.out.println("Server finished"); } }
32
class Client implements Runnable {
private int m_id; private CountDownLatch m_latchObject; public Client(int id, CountDownLatch latchObject){ m_id = id; m_latchObject = latchObject; } public void run () { synchronized (System.out) { System.out.println("Client #" + m_id + " started"); } try { Thread.sleep(200); } catch (InterruptedException e) {} synchronized (System.out){ System.out.println("Client #" + m_id + " doing something"); } try { Thread.sleep(200); } catch (InterruptedException e) {} System.out.println("Client #" + m_id + " finished"); m_latchObject.countDown(); } }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.