Programming with Shared Memory Java Threads and Synchronization

  • Slides: 25
Download presentation
Programming with Shared Memory Java Threads and Synchronization Brief Review ITCS 4145/5145, Parallel Programming

Programming with Shared Memory Java Threads and Synchronization Brief Review ITCS 4145/5145, Parallel Programming B. Wilkinson Oct 10, 2013 slides 8 c. ppt. slides 8 c-1

Thread class Each thread is an object of the Thread class. (More accurately “Each

Thread class Each thread is an object of the Thread class. (More accurately “Each thread is associated with an instance of the class Thread. ”*) Java provide two basic ways to creates a thread: 1. Define a class that is derived class of the class Thread. 2. Make your class implement the Runnable interface * http: //java. sun. com/docs/books/tutorial/essential/concurrency/ 2

Simplest way is: 1. Define a class that is derived class of the class

Simplest way is: 1. Define a class that is derived class of the class Thread. • Object of this class is a thread. • Provide a method called run (which will override the inherited run method that does nothing). • The run method defines the code for the thread. • Invoke the start method, which initiates the computation of the thread 3

Example public class Hello. Thread extends Thread { public void run() { System. out.

Example public class Hello. Thread extends Thread { public void run() { System. out. println("Hello from a thread!"); } Java entry point public static void main(String args[ ]) { } Create Hello. Thread my. Thread = new Hello. Thread(); Thread object my. Thread. start(); Start thread and execute run method } 4

The Thread class actually implements the interface called Runnable. The Runnable interface defines the

The Thread class actually implements the interface called Runnable. The Runnable interface defines the single method, run, meant to contain the code executed in the thread. Alternate more powerful way to create threads: 2. Make your class explicitly implement the Runnable interface 5

Example Explicitly Implementing Runnable Interface public class Hello. Runnable implements Runnable { public void

Example Explicitly Implementing Runnable Interface public class Hello. Runnable implements Runnable { public void run() { System. out. println("Hello from a thread!"); } public static void main(String args[ ]) { Hello. Runnable my. Thread = new Hello. Runnable(); // Runnable object Thread tr = new Thread(my. Thread); // Create Thread object tr. start(); // Start thread and execute run method } } 6

Advantage is Runnable object can subclass a class other than Thread, i. e. :

Advantage is Runnable object can subclass a class other than Thread, i. e. : public class My. Runnable extends Some. Class implements Runnable { public void run() { System. out. println("Hello from a thread!"); } public static void main(String args[ ]) { Hello. Runnable my. Thread = new Hello. Runnable(); Thread tr = new Thread(my. Thread); tr. start(); } } Note: both Thread class and Runnable interface are part of the standard Java libraries (java. lang package) 7

A Program with Three Java Threads using 1 st method class A extends Thread

A Program with Three Java Threads using 1 st method class A extends Thread { public void run() { for(int i=1; i<=5; i++) System. out. println("t From Thread. A: i= "+i); System. out. println("Exit from A"); } } class B extends Thread { public void run() { for(int j=1; j<=5; j++) System. out. println("t From Thread. B: j= "+j); System. out. println("Exit from B"); } } class C extends Thread { public void run() { for(int k=1; k<=5; k++) System. out. println("t From Thread. C: k= "+k); System. out. println("Exit from C"); } } class Thread. Test { public static void main(String args[]) { new A(). start(); new B(). start(); new C(). start(); } } Based on Raj Buyya’s slides 8

Sample Output Run 2 From Thread. A: i= 1 From Thread. A: i= 2

Sample Output Run 2 From Thread. A: i= 1 From Thread. A: i= 2 From Thread. A: i= 3 From Thread. A: i= 4 From Thread. A: i= 5 Exit from A From Thread. C: k= 1 From Thread. C: k= 2 From Thread. C: k= 3 From Thread. C: k= 4 From Thread. C: k= 5 Exit from C From Thread. B: j= 1 From Thread. B: j= 2 From Thread. B: j= 3 From Thread. B: j= 4 From Thread. B: j= 5 Exit from B From Thread. A: i= 1 From Thread. A: i= 2 From Thread. A: i= 3 From Thread. A: i= 4 From Thread. A: i= 5 From Thread. C: k= 1 From Thread. C: k= 2 From Thread. C: k= 3 From Thread. C: k= 4 From Thread. C: k= 5 Exit from C From Thread. B: j= 1 From Thread. B: j= 2 From Thread. B: j= 3 From Thread. B: j= 4 From Thread. B: j= 5 Exit from B Exit from A 9

Thread class Various instance and class methods, setters and getters: • Class methods: •

Thread class Various instance and class methods, setters and getters: • Class methods: • sleep() • … • Instance methods: • destroy() • interrupt() • join() • start() • … • Depreciated methods (unsafe and can cause deadlock) • resume(), stop() suspend() 10

Thread. sleep causes the current thread to suspend execution for a specified period. Example

Thread. sleep causes the current thread to suspend execution for a specified period. Example Sleep to print messages at four-second intervals: public class Sleep. Messages { public static void main(String args[]) throws Interrupted. Exception { String important. Info[] = { exception that sleep throws "Mares eat oats", when another thread "Does eat oats", interrupts current thread "Little lambs eat ivy", while sleep is active. Not "A kid will eat ivy too" caught in sample code. }; for (int i = 0; i < important. Info. length; i++) { Thread. sleep(4000); //Pause for 4 seconds System. out. println(important. Info[i]); //Print a message } } } 11

Java Synchonization Java provides Synchronized keyword to methods that cause only one invocation of

Java Synchonization Java provides Synchronized keyword to methods that cause only one invocation of a synchronized method on the same object at a time. Example public class Synchronized. Counter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } 12

Implementation of Java synchronization Every object has an intrinsic lock associated with it. A

Implementation of Java synchronization Every object has an intrinsic lock associated with it. A thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it is done with them. Note this is used to ensure only one synchronized method at a time. Does not affect other methods of object. Roughly a “Monitor” depending on how we define a monitor. (see: http: //en. wikipedia. org/wiki/Monitor_%28 synchronization%29) 13

Example using synchronized methods On-line banking Suppose an account can be accessed potentially simultaneously

Example using synchronized methods On-line banking Suppose an account can be accessed potentially simultaneously by different entities - maybe a joint account, maybe automatic debits, … Suppose three entities each trying to perform an operation, either: • deposit() • withdraw() • enquire() 14

Synchronized account methods class Account { int balance; // if 'synchronized' is removed, outcome

Synchronized account methods class Account { int balance; // if 'synchronized' is removed, outcome unpredictable public synchronized void deposit( ) { balance += deposit_amount; } public synchronized void withdraw( ) { balance -= deposit_amount; } public synchronized void enquire( ) { … // display balance. } } 15

Create threads, one for each entity class Internet. Banking. System { Java entry point

Create threads, one for each entity class Internet. Banking. System { Java entry point public static void main(String [] args ) { Account account. Object = new Account (); Thread t 1 = new Thread(new My. Thread(account. Object)); Thread t 2 = new Thread(new Your. Thread(account. Object)); Thread t 3 = new Thread(new Her. Thread(account. Object)); t 1. start(); t 2. start(); t 3. start(); Start threads and execute run method of each one // DO some other operation } // end main() } Based on Raj Buyya’s slides, “Multithreaded Programming using Java Threads” www. buyya. com 16

class My. Thread implements Runnable { Account account; public My. Thread (Account s) {

class My. Thread implements Runnable { Account account; public My. Thread (Account s) { account = s; } public void run() { account. deposit(); } } // end class My. Thread class Your. Thread implements Runnable { Account account; public Your. Thread (Account s) { account = s; } public void run() { account. withdraw(); } } // end class Your. Thread class Her. Thread implements Runnable { Account account; public Her. Thread (Account s) { account = s; } public void run() { account. enquire(); } } // end class Her. Thread Shared account (shared object) 17

Another example, adding numbers from an array 18

Another example, adding numbers from an array 18

19

19

20

20

atomic action An atomic action cannot stop in the middle - it either happens

atomic action An atomic action cannot stop in the middle - it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete. Read/writes can be declared atomic with the volatile keyword, e. g. private volatile int x; Sometimes can be more efficient than synchronized methods. 21

Synchronized Statements Unlike synchronized methods, synchronized statements must specify object that provides intrinsic lock.

Synchronized Statements Unlike synchronized methods, synchronized statements must specify object that provides intrinsic lock. Uses construct: Evaluate to an object or an array. Used to identify lock. synchronized ( expression ) { … statements “critical section” } Example public void add. Name(String name) { synchronized(this) { last. Name = name; Only this part synchronized name. Count++; } name. List. add(name); } 22

Coordinating threads Wait/notify mechanism Sometimes need a thread to stop running and wait for

Coordinating threads Wait/notify mechanism Sometimes need a thread to stop running and wait for an event before continuing. wait() and notify() methods are methods of class Object. Every object can maintain a list of waiting threads. wait() When a thread calls wait() method of an object, any locks the thread holds are temporarily released and thread added to list of waiting threads for that object and stops running. notify() When another thread calls notify() method on the same object, object wakes up one of the waiting threads and allows it to continue. 23

Join Sometimes one thread needs to stop and wait for another thread to complete.

Join Sometimes one thread needs to stop and wait for another thread to complete. join() -- waits for a thread to die, i. e. thr 1. join() waits for thread thr 1 to die. Calling return() from the run method implicitly causes the thread to exit. 24

More information http: //java. sun. com/docs/books/tutorial/essential/ concurrency/ 25

More information http: //java. sun. com/docs/books/tutorial/essential/ concurrency/ 25