Java Threads and Synchronization Review Modified from slides

  • Slides: 31
Download presentation
Java Threads and Synchronization Review Modified from slides taken from http: //coitweb. uncc. edu/~abw/ITCS

Java Threads and Synchronization Review Modified from slides taken from http: //coitweb. uncc. edu/~abw/ITCS 4145 S 13/slides 8 c. ppt Based upon the Java tutorial at http: //java. sun. com/docs/books/tutorial/essential/concurrency/ More in-depth tutorial available at http: //tutorials. jenkov. com/java-concurrency/index. html 1

Thread class Each thread is an object of the Thread class. (Java tutorial says:

Thread class Each thread is an object of the Thread class. (Java tutorial says: “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 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 the method called run (which will override the inherited run method, which 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

Simpler version if name of thread object not needed public class Hello. Thread extends

Simpler version if name of thread object not needed public class Hello. Thread extends Thread { public void run() { System. out. println("Hello from a thread!"); } public static void main(String args[ ]) { (new Hello. Thread()). start(); } } However, usually one does need the object by name to apply other thread methods. 5

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 6

Example public class Hello. Runnable implements Runnable { public void run() { System. out.

Example 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 7

Slightly simplified version: public class Hello. Runnable implements Runnable { public void run() {

Slightly simplified version: public class Hello. Runnable implements Runnable { public void run() { System. out. println("Hello from a thread!"); } public static void main(String args[ ]) { Thread tr = new Thread(new Hello. Runnable()) tr. start(); } } Even simpler if thread object name not needed: public class Hello. Runnable implements Runnable { public void run() { System. out. println("Hello from a thread!"); } public static void main(String args[ ]) { (new Thread(new Hello. Runnable())). start(); } } 8

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

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[ ]) { (new Thread(new Hello. Runnable())). start(); } } Note: both the Thread class and the Runnable interface are part of the standard Java libraries (java. lang package) 9

Thread Priority • In Java, each thread assigned priority, which affects the order in

Thread Priority • In Java, each thread assigned priority, which affects the order in which it is scheduled for running. • Threads so far had same default priority (NORM_PRIORITY) and they are served using FCFS policy. • Java allows users to change priority: • Thread. Name. set. Priority(int. Number) – MIN_PRIORITY = 1 – NORM_PRIORITY=5 – MAX_PRIORITY=10 Based on Raj Buyya’s slides 10

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() 11

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 } } } 12

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; } } 13

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. 14

Example using synchronized methods On-line banking Several entities can access account potentially simultaneously (maybe

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

Create threads, one for each entities class Internet. Banking. System { public static void

Create threads, one for each entities class Internet. Banking. System { 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(); // DO some other operation } // end main() } Based on Raj Buyya’s slides 16

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

Shared account 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 account (shared object) class Her. Thread implements Runnable { Account account; public Her. Thread (Account s) { account = s; } public void run() {account. enquire(); } } // end class Her. Thread 17

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. } } 18

Synchronized Statements Unlike synchronized methods, synchronized statements must specify the object that provides the

Synchronized Statements Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: Uses construct ion: synchronized ( expression ) { statements Evaluate to an object or an array. Used to identify lock. “critical section” } 19

Synchronized Statements Example public void add. Name(String name) { synchronized(this) { last. Name =

Synchronized Statements Example public void add. Name(String name) { synchronized(this) { last. Name = name; Only this part name. Count++; synchronized } name. List. add(name); } 20

Synchronized Statements Example class Account { static synchronized void lookup(String name) { … }

Synchronized Statements Example class Account { static synchronized void lookup(String name) { … } } is equivalent to class Account { static void lookup(String name) { synchronized(Account. class) { … } } } 21

atomic action An atomic action cannot stop in the middle: it either happens completely,

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. 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(), notify(), and notify. All() methods are methods of class Object. They must be called by a thread currently holding this object’s lock; otherwise an Illegal. Monitor. State. Exception is thrown. Every object can maintain a list of waiting threads. 23

Coordinating threads Wait/notify mechanism Every object can maintain a list of waiting threads. wait()

Coordinating threads Wait/notify mechanism Every object can maintain a list of waiting threads. wait() When a thread calls wait() method of an object, it release this lock, and thread is added to list of waiting threads for that object and stops running. notify() When another thread calls notify() method on the same object, one of the waiting threads is unblocked and allows it to continue. The choice is arbitrary. notify. All() continue. All waiting threads are unblocked and can 24

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. 25

Read/Write Synchronization: Version 1 (Allow Multiple Readers) public class Database { public Database() {

Read/Write Synchronization: Version 1 (Allow Multiple Readers) public class Database { public Database() { reader. Count = 0; db. Writing = false; } public synchronized int start. Read() { /* see next slides */ } public synchronized int end. Read() { /* see next slides */ } public synchronized void start. Write() { /*see next slides*/ } public synchronized void end. Write() { /*see next slides*/ } private int reader. Count; private boolean db. Writing; }

start. Read() and end. Read() public synchronized int start. Read() { while (db. Writing

start. Read() and end. Read() public synchronized int start. Read() { while (db. Writing == true) { try { wait(); } catch (Interrupted. Exception e) { } } reader. Count++; return reader. Count; } public synchronized int end. Read() { reader. Count--; if (reader. Count == 0) db. notify. All(); return reader. Count; }

Writer Methods public synchronized void start. Write() { while (reader. Count > 0 ||

Writer Methods public synchronized void start. Write() { while (reader. Count > 0 || db. Writing == true) { try { wait(); } catch (Interrupted. Exception e) { } } db. Writing = true; } public synchronized void end. Write() { db. Writing = false; notify. All(); }

Read/Write Synchronization: Version 2 (Writer preferred) public class Database { public Database() { reader.

Read/Write Synchronization: Version 2 (Writer preferred) public class Database { public Database() { reader. Count = 0; waiting. Writers = 0; db. Writing = false; } public synchronized int start. Read() { /* see next slides */ } public synchronized int end. Read() { /* see next slides */ } public synchronized void start. Write() { /*see next slides*/ } public synchronized void end. Write() { /*see next slides*/ } private int reader. Count; private int waiting. Writers; private boolean db. Writing; } // # of writers running/waiting

start. Read() and end. Read() public synchronized int start. Read() { while (db. Writing

start. Read() and end. Read() public synchronized int start. Read() { while (db. Writing == true || waiting. Writers > 0) { try { wait(); } catch (Interrupted. Exception e) { } } reader. Count++; return reader. Count; } public synchronized int end. Read() { reader. Count--; if (reader. Count == 0) db. notify. All(); return reader. Count; }

Writer Methods public synchronized void start. Write() { waiting. Writers++; while (reader. Count >

Writer Methods public synchronized void start. Write() { waiting. Writers++; while (reader. Count > 0 || db. Writing == true) { try { wait(); } catch (Interrupted. Exception e) { } } db. Writing = true; } public synchronized void end. Write() { waiting. Writers--; db. Writing = false; notify. All(); }