Lecture12

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Lecture12 as PDF for free.

More details

  • Words: 7,268
  • Pages: 109
Threads in Java

Monitors

Embedded Systems Programming Lecture 12 Ver´ onica Gaspes www2.hh.se/staff/vero

Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Threads in Java class A{ ... public static void main(String[] cmndLn){ ... new Thread(new T1()).start(); new T2().start(); ... } } class T1 implements Runnable { public void run(){...} }

class T2 extends Thread { public void run(){...} }

Threads in Java

Monitors

Remote Method Invocation

Threads in Java class A{ ... public static void main(String[] cmndLn){ ... new Thread(new T1()).start(); new T2().start(); ... } } class T1 implements Runnable { public void run(){...} }

class T2 extends Thread { public void run(){...} }

Threads in Java

Monitors

Remote Method Invocation

Threads in Java class A{ ... public static void main(String[] cmndLn){ ... new Thread(new T1()).start(); new T2().start(); ... } } class T1 implements Runnable { public void run(){...} }

class T2 extends Thread { public void run(){...} }

Threads in Java

Monitors

Remote Method Invocation

Threads in Java class A{ ... public static void main(String[] cmndLn){ ... new Thread(new T1()).start(); new T2().start(); ... } } class T1 implements Runnable { public void run(){...} }

class T2 extends Thread { public void run(){...} }

Threads in Java

Monitors

Monitors in the real world . . . Lizards

Remote Method Invocation

Threads in Java

Monitors

Monitors in the real world . . . Screens

Remote Method Invocation

Threads in Java

Monitors

Monitors in the real world . . . Submarines

Remote Method Invocation

Threads in Java

Monitors

Monitors in programming languages . . . A language approach to synchronization

Remote Method Invocation

Threads in Java

Monitors

An Abstract Data Type . . . The Counter example class Counter{ private int x = 0; public void inc(){ int tmp = x; tmp++; x = tmp; } public int read(){ return x; } }

Remote Method Invocation

Threads in Java

Monitors

An Abstract Data Type . . . The Counter example class Counter{ private int x = 0; public void inc(){ int tmp = x; tmp++; x = tmp; } public int read(){ return x; } }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

. . . that supports Mutual Exclusion

import java.util.concurrency.locks.*; class Counter{ private final Lock lock = new ReentrantLock(); private int x = 0; public void inc(){ lock.lock(); try{ int tmp = x; tmp++; x = tmp; }finally{lock.unlock();} }

Threads in Java

Monitors

Remote Method Invocation

What does this mean? The abstract data type can be shared by many threads while preserving the integrity of the representation! Only one thread at a time is allowed to be using the monitor. All other threads are blocked until they can be given permission to enter.

Example void main(String args[]){ Counter cnt = new Counter(); Thread [] turns = new Thread[10]; for(int i = 0; i<10;i++){ turns[i] = new CounterUser(cnt); turns[i].start(); } }

Threads in Java

Monitors

Remote Method Invocation

What does this mean? The abstract data type can be shared by many threads while preserving the integrity of the representation! Only one thread at a time is allowed to be using the monitor. All other threads are blocked until they can be given permission to enter.

Example void main(String args[]){ Counter cnt = new Counter(); Thread [] turns = new Thread[10]; for(int i = 0; i<10;i++){ turns[i] = new CounterUser(cnt); turns[i].start(); } }

Threads in Java

Monitors

Remote Method Invocation

What does this mean? The abstract data type can be shared by many threads while preserving the integrity of the representation! Only one thread at a time is allowed to be using the monitor. All other threads are blocked until they can be given permission to enter.

Example void main(String args[]){ Counter cnt = new Counter(); Thread [] turns = new Thread[10]; for(int i = 0; i<10;i++){ turns[i] = new CounterUser(cnt); turns[i].start(); } }

Threads in Java

Monitors

Remote Method Invocation

What does this mean? The abstract data type can be shared by many threads while preserving the integrity of the representation! Only one thread at a time is allowed to be using the monitor. All other threads are blocked until they can be given permission to enter.

Example void main(String args[]){ Counter cnt = new Counter(); Thread [] turns = new Thread[10]; for(int i = 0; i<10;i++){ turns[i] = new CounterUser(cnt); turns[i].start(); } }

Threads in Java

Monitors

Remote Method Invocation

What does this mean? The abstract data type can be shared by many threads while preserving the integrity of the representation! Only one thread at a time is allowed to be using the monitor. All other threads are blocked until they can be given permission to enter.

Example void main(String args[]){ Counter cnt = new Counter(); Thread [] turns = new Thread[10]; for(int i = 0; i<10;i++){ turns[i] = new CounterUser(cnt); turns[i].start(); } }

Threads in Java

Monitors

Remote Method Invocation

The threads

Example class CounterUser extends Thread{ private Counter counter; public CounterUser(Counter c){counter = c;} public void run(){ while(true) counter.inc(); } }

Threads in Java

Monitors

Remote Method Invocation

And support for Condition Synchronization With more elaborate abstract data types, threads might need to be blocked until some condition holds for the abstract datatype. Example In the bounded buffer that is shared by producer threads and consumer threads: Producers might have to wait until the buffer is not full. Consumers might have to wait until the buffer is not empty. Languages supporting monitors provide a type for condition variables. We first discuss their purpose and expected operations. Then we look at Java. Then we do an example.

Threads in Java

Monitors

Remote Method Invocation

And support for Condition Synchronization With more elaborate abstract data types, threads might need to be blocked until some condition holds for the abstract datatype. Example In the bounded buffer that is shared by producer threads and consumer threads: Producers might have to wait until the buffer is not full. Consumers might have to wait until the buffer is not empty. Languages supporting monitors provide a type for condition variables. We first discuss their purpose and expected operations. Then we look at Java. Then we do an example.

Threads in Java

Monitors

Remote Method Invocation

And support for Condition Synchronization With more elaborate abstract data types, threads might need to be blocked until some condition holds for the abstract datatype. Example In the bounded buffer that is shared by producer threads and consumer threads: Producers might have to wait until the buffer is not full. Consumers might have to wait until the buffer is not empty. Languages supporting monitors provide a type for condition variables. We first discuss their purpose and expected operations. Then we look at Java. Then we do an example.

Threads in Java

Monitors

Remote Method Invocation

And support for Condition Synchronization With more elaborate abstract data types, threads might need to be blocked until some condition holds for the abstract datatype. Example In the bounded buffer that is shared by producer threads and consumer threads: Producers might have to wait until the buffer is not full. Consumers might have to wait until the buffer is not empty. Languages supporting monitors provide a type for condition variables. We first discuss their purpose and expected operations. Then we look at Java. Then we do an example.

Threads in Java

Monitors

Remote Method Invocation

And support for Condition Synchronization With more elaborate abstract data types, threads might need to be blocked until some condition holds for the abstract datatype. Example In the bounded buffer that is shared by producer threads and consumer threads: Producers might have to wait until the buffer is not full. Consumers might have to wait until the buffer is not empty. Languages supporting monitors provide a type for condition variables. We first discuss their purpose and expected operations. Then we look at Java. Then we do an example.

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Monitors offer Condition Variables Used to Delay a process that cannot safely continue executing until the monitor’s state satisfies some property. Awaken a delayed process when the property holds. How? 1 Inside a monitor declare a variable of the type for condition variables cond cv . 2

A process blocks on a condition variable by executing wait(cv) .

3

Processes that are blocked on condition variables get awaken by signal(cv) .

Threads in Java

Monitors

Remote Method Invocation

Semantics

Values The value of a condition variable is a queue of delayed processes. Wait The process that executes wait(cv) gets delayed at the rear of the queue for cv. It relinquishes exclusive access to the monitor. Signal Execution of signal(cv) examines cv’s queue. If it is empty it has no effect. If there are delayed porcesses, it awakens the process at the front of the queue.

Threads in Java

Monitors

Remote Method Invocation

Semantics

Values The value of a condition variable is a queue of delayed processes. Wait The process that executes wait(cv) gets delayed at the rear of the queue for cv. It relinquishes exclusive access to the monitor. Signal Execution of signal(cv) examines cv’s queue. If it is empty it has no effect. If there are delayed porcesses, it awakens the process at the front of the queue.

Threads in Java

Monitors

Remote Method Invocation

Semantics

Values The value of a condition variable is a queue of delayed processes. Wait The process that executes wait(cv) gets delayed at the rear of the queue for cv. It relinquishes exclusive access to the monitor. Signal Execution of signal(cv) examines cv’s queue. If it is empty it has no effect. If there are delayed porcesses, it awakens the process at the front of the queue.

Threads in Java

Monitors

Remote Method Invocation

Semantics

Values The value of a condition variable is a queue of delayed processes. Wait The process that executes wait(cv) gets delayed at the rear of the queue for cv. It relinquishes exclusive access to the monitor. Signal Execution of signal(cv) examines cv’s queue. If it is empty it has no effect. If there are delayed porcesses, it awakens the process at the front of the queue.

Threads in Java

Monitors

Remote Method Invocation

Semantics - signaling disciplines Who will get to run when a process does signal(cv)? The signaling process? The newly awaken process? Signal and Continue The signaler continues, the signaled process executes at some later time. Signal and Wait The signaler waits until some other time and the signaled process executes now. Signal and Continue is implemented in Unix, Java and PThreads. It is compatible with priority scheduling, programs are easier to understand.

Threads in Java

Monitors

Remote Method Invocation

Semantics - signaling disciplines Who will get to run when a process does signal(cv)? The signaling process? The newly awaken process? Signal and Continue The signaler continues, the signaled process executes at some later time. Signal and Wait The signaler waits until some other time and the signaled process executes now. Signal and Continue is implemented in Unix, Java and PThreads. It is compatible with priority scheduling, programs are easier to understand.

Threads in Java

Monitors

Remote Method Invocation

Semantics - signaling disciplines Who will get to run when a process does signal(cv)? The signaling process? The newly awaken process? Signal and Continue The signaler continues, the signaled process executes at some later time. Signal and Wait The signaler waits until some other time and the signaled process executes now. Signal and Continue is implemented in Unix, Java and PThreads. It is compatible with priority scheduling, programs are easier to understand.

Threads in Java

Monitors

Remote Method Invocation

Semantics - signaling disciplines Who will get to run when a process does signal(cv)? The signaling process? The newly awaken process? Signal and Continue The signaler continues, the signaled process executes at some later time. Signal and Wait The signaler waits until some other time and the signaled process executes now. Signal and Continue is implemented in Unix, Java and PThreads. It is compatible with priority scheduling, programs are easier to understand.

Threads in Java

What we don’t see ...

Monitors

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

java.util.concurrent.locks Monitors (locks and condition types) are provided in the package java.util.concurrent.locks

The interface Condition Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to ”wait”) until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread.

Threads in Java

Monitors

Remote Method Invocation

java.util.concurrent.locks Monitors (locks and condition types) are provided in the package java.util.concurrent.locks

The interface Condition Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to ”wait”) until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread.

Threads in Java

Monitors

Remote Method Invocation

java.util.concurrent.locks A Condition instance is intrinsically bound to a lock. To obtain a Condition instance for a particular Lock instance use its newCondition() method. Example class BoundedBuffer{ private Lock lock private Condition notFull private Condition notEmpty private int count private int n; private T[] buf; private int front = 0; private int rear = 0; ...}

= = = =

new ReentrantLock(); lock.newCondition(); lock.newCondition(); 0;

Threads in Java

Monitors

Remote Method Invocation

java.util.concurrent.locks A Condition instance is intrinsically bound to a lock. To obtain a Condition instance for a particular Lock instance use its newCondition() method. Example class BoundedBuffer{ private Lock lock private Condition notFull private Condition notEmpty private int count private int n; private T[] buf; private int front = 0; private int rear = 0; ...}

= = = =

new ReentrantLock(); lock.newCondition(); lock.newCondition(); 0;

Threads in Java

Monitors

Using Condition Example public void deposit(T item){ lock.lock(); try{ while(count == n) notFull.await(); buf[rear] = item; rear = inc(rear); count++; notEmpty.signal(); }catch(InterruptedException e){ System.out.println(e.getMessage());} finally{ lock.unlock(); } }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Using Condition Example public T fetch(){ lock.lock(); try{ while(count == 0) notEmpty.await(); T result = buf[front]; front = inc(front); count--; notFull.signal(); return result; }catch(InterruptedException e){ System.out.println(e.getMessage());return null;} finally{ lock.unlock(); } }

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Readers & Writers - problem statement

Two kinds of processes (Readers and Writers) share a database. Readers execute transactions that examine database records. Writers execute transactions that both examine and update database records. The database is consistent initially and transactions, if performed in isolation, preserve consistency. A writer must have exclusive access to the database. Assuming no writer is using the database, any number of readers may concurrently execute transactions.

Threads in Java

Monitors

Remote Method Invocation

Scheduling readers and writers

The scheduler has 2 roles: Schedule requests. Ensure that no writer is using the database when readers are using it. Ensure that only one writer at a time uses the database.

Threads in Java

Monitors

Remote Method Invocation

Scheduling readers and writers Writers have to follow 1

Request permission to write

2

Write

3

Release the database

Readers have to follow 1

Request permission to read

2

Read

3

Release the database

Threads in Java

Monitors

Organizing the program in Java

import java.util.concurrent.locks.*; class RWScheduler{ public void requestRead() public void requestWrite() public void releaseRead() public void releaseWrite() }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Organizing the program in Java class Reader extends Thread{ private RWScheduler rws; private DB db; public Reader(int id, RWScheduler rws, DB db){ this.rws = rws; this.db = db; } public void run(){ while(true){ rws.requestRead(); db.read(); rws.releaseRead(); } }

Threads in Java

Monitors

Remote Method Invocation

Organizing the program in Java class Writer extends Thread{ private RWScheduler rws; private DB db; public Writer(int id, RWScheduler rws, DB db){ this.rws = rws; this.db = db; } public void run(){ while(true){ rws.requestWrite(); db.write(...); rws.releaseWrite(); } }

Threads in Java

Monitors

Remote Method Invocation

How do we program the scheduler?

The scheduler has to delay readers and/or writers until they have the right to use the database. For doing so, it counts the number of readers and number of writers using the db. The scheduler has to wake up readers and/or writers following some policy. For doing so, it counts the number of delayed readers and writers.

Threads in Java

Monitors

Remote Method Invocation

Scheduler code

import java.util.concurrent.locks.*; class RWScheduler{ private private private private

int int int int

nr nw dr dw

= = = =

0; 0; 0; 0;

private ReentrantLock lock = new ReentrantLock(); private Condition reader = lock.newCondition(); private Condition writer = lock.newCondition();

Threads in Java

Monitors

Remote Method Invocation

Scheduler code — requestRead import java.util.concurrent.locks.*; class RWScheduler{ public void requestRead(){ lock.lock(); try{ while(nw > 0) {dr++;reader.await();} nr++; if(nr==1){dr=0;reader.signalAll();} }catch(InterruptedException e){} finally{lock.unlock();} } Can writers starve?

Threads in Java

Monitors

Remote Method Invocation

Scheduler code — releaseRead

import java.util.concurrent.locks.*; class RWScheduler{ public void releaseRead(){ lock.lock(); try{ nr--; if(nr==0 && dw>0){dw--;writer.signal();} }finally{lock.unlock();} }

Threads in Java

Monitors

Remote Method Invocation

Scheduler code — requestWrite

import java.util.concurrent.locks.*; class RWScheduler{ public void requestWrite(){ lock.lock(); try{ while(nw > 0 || nr >0) {dw++;writer.await();} nw++; }catch(InterruptedException e){} finally{lock.unlock();} }

Threads in Java

Monitors

Scheduler code — releaseWrite

import java.util.concurrent.locks.*; class RWScheduler{ public void releaseWrite(){ lock.lock(); try{ nw--; if(dr>0){dr--;reader.signal();} else{dw--;writer.signal();} }finally{lock.unlock();} }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Monitors

We said that monitors are abstract data types with support for 1

mutual exclusion

2

waiting on conditions

But, where are the threads? We have to spend some time thinking how to organize our programs.

Threads in Java

Monitors

Remote Method Invocation

Monitors We said that monitors are abstract data types with support for 1

mutual exclusion

2

waiting on conditions

But, where are the threads? We have to spend some time thinking how to organize our programs.

Threads in Java

Monitors

Remote Method Invocation

Monitors We said that monitors are abstract data types with support for 1

mutual exclusion

2

waiting on conditions

But, where are the threads? We have to spend some time thinking how to organize our programs.

Threads in Java

Monitors

An object will be shared by many threads . . . Example class BoundedBuffer{ private int n; private T[] buf; private int front = 0; private int rear = 0; /* constructor */ public BoundedBuffer(int size) /* operations */ public void deposit(T item){ buf[rear] = item; rear = inc(rear); } public T fetch(){...} }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Make it thread safe (make it a monitor!) Example import java.util.concurrent.locks.*; class BoundedBuffer{ private Lock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); private int count = 0; public void deposit(T item){ lock.lock(); try{ while(count == n) notFull.await(); buf[rear] = item; rear = inc(rear); count++; notEmpty.signal(); }catch(...){...}finally{lock.unlock();

Threads in Java

Monitors

Now many threads can use it concurrently . . .

Example public static void main(String[] args){ BoundedBuffer theBuffer = new BoundedBuffer(5); for(int i = 1;i<10;i++){ new Producer(theBuffer, i).start(); } for(int i = 1;i<5;i++){ new Consumer(theBuffer, i).start(); } }

Remote Method Invocation

Threads in Java

Monitors

Remote Method Invocation

Now many threads can use it concurrently . . . Example class Producer extends Thread{ private BoundedBuffer bb; private int id; private Random random = new Random(); public Producer(BoundedBuffer bb, int id){ this.bb = bb;this.id = id; } public void run(){ int x; while(true){ nap(random.nextInt(5000)); x = random.nextInt(100); bb.deposit(x); }

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

What happens to the threads? In a concurrent program, many threads will be making progress simultaneously. If many threads share an instance of BoundedBuffer, only one will get to execute fetch or deposit at a time! (they appear to be atomic!) And the other threads? They are put to sleep waiting for permission to run the method they want!

There is also an explicit way of putting threads to sleep, namely the method await on a condition variable! And a way of explicitely waking a thread, namely the method signal on a condition variable. Who does a signal? Another thread that when running discovers that it has made some condition valid!

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

Remote Objects in Java

Java supports this style of distributed programs with the libraries in the package java.rmi A remote server object running some background threads and offering some methods is defined in two stages: 1

2

An interface declares the methods that can be called from other virtual machines, A class implements this interface

A remote server object is put to work by 1

Creating an instance using a constructor.

2

Installing it as a remote object on a port.

3

Binding a name to this object at its port.

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display

Example A display showing the arrival or departure times of aircraft at an airport. It can be used by all the airlines to publish info about their flights.

Example A client process running on the computer of the airline operator can add an info line by calling addRow remove an info line by calling deleteRow Multiple clients might call addRow and deleteRow at the same time Several processes will serve these calls concurrently!

Threads in Java

Monitors

Remote Method Invocation

An airport display as a remote server Define the interface saying what methods can be invoked remotely: Example import java.rmi.Remote; import java.rmi.RemoteException; public interface HighLevelDisplay extends Remote{ public void clear() throws RemoteException; public void addRow(String str) throws RemoteException; public void deleteRow(int row) throws RemoteException; } Remote methods will report network-related failures by throwing RemoteException

Threads in Java

Monitors

Remote Method Invocation

Remote airport display Implement the remote interface (with an ordinary class!) Example public class JDisplay2 implements HighLevelDisplay { ... public void addRow(String str) { updateRow(usedRows,str); flashRow(usedRows,1000); usedRows++; } ... The implementation of the method addRow doesn’t need to declare that it throws RemoteException.

Threads in Java

Monitors

Remote Method Invocation

Remote airport display Implement the remote interface (with an ordinary class!) Example public class JDisplay2 implements HighLevelDisplay { ... public void addRow(String str) { updateRow(usedRows,str); flashRow(usedRows,1000); usedRows++; } ... The implementation of the method addRow doesn’t need to declare that it throws RemoteException.

Threads in Java

Monitors

Remote Method Invocation

Remote airport display Implement the remote interface (with an ordinary class!) Example public class JDisplay2 implements HighLevelDisplay { ... public void addRow(String str) { updateRow(usedRows,str); flashRow(usedRows,1000); usedRows++; } ... The implementation of the method addRow doesn’t need to declare that it throws RemoteException.

Threads in Java

Monitors

Remote Method Invocation

Installing the server A server class creates an instance of this remote object, exports it and names it. Example public static void main(String args[]){ try{ HighLevelDisplay hld = new JDisplay2(); HighLevelDisplay stub =

(HighLevelDisplay)UnicastRemoteObject.exportObject(hld,0);

java.rmi.registry.Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); System.err.println("Display ready"); }catch(Exception e){...} }

Threads in Java

Monitors

Remote Method Invocation

Installing the server A server class creates an instance of this remote object, exports it and names it. Example public static void main(String args[]){ try{ HighLevelDisplay hld = new JDisplay2(); HighLevelDisplay stub =

(HighLevelDisplay)UnicastRemoteObject.exportObject(hld,0);

java.rmi.registry.Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); System.err.println("Display ready"); }catch(Exception e){...} }

Threads in Java

Monitors

Remote Method Invocation

Exporting remote objects In order to make an object remote it is not enough to create an instance of it as with HighLevelDisplay

hld = new JDisplay2();

The java RMI runtime (doing a lot behind the scenes!) has to be able to receive remote invocations. We say that the object is exported: HighLevelDisplay stub = (HighLevelDisplay)UnicastRemoteObject.exportObject(hld,0);

The runtime may begin to listen on a new server socket or may use a shared server socket to accept incoming remote calls for the remote object.

Threads in Java

Monitors

Remote Method Invocation

Exporting remote objects In order to make an object remote it is not enough to create an instance of it as with HighLevelDisplay

hld = new JDisplay2();

The java RMI runtime (doing a lot behind the scenes!) has to be able to receive remote invocations. We say that the object is exported: HighLevelDisplay stub = (HighLevelDisplay)UnicastRemoteObject.exportObject(hld,0);

The runtime may begin to listen on a new server socket or may use a shared server socket to accept incoming remote calls for the remote object.

Threads in Java

Monitors

Remote Method Invocation

Register remote objects

An object wanting to call a method exported by a remote object will have to acquire a stub for this object. Programs register remote services to allow this Example Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); Callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object. A utility program (rmiregistry) is used to build the registry.

Threads in Java

Monitors

Remote Method Invocation

Register remote objects

An object wanting to call a method exported by a remote object will have to acquire a stub for this object. Programs register remote services to allow this Example Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); Callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object. A utility program (rmiregistry) is used to build the registry.

Threads in Java

Monitors

Remote Method Invocation

Register remote objects

An object wanting to call a method exported by a remote object will have to acquire a stub for this object. Programs register remote services to allow this Example Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); Callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object. A utility program (rmiregistry) is used to build the registry.

Threads in Java

Monitors

Remote Method Invocation

Register remote objects

An object wanting to call a method exported by a remote object will have to acquire a stub for this object. Programs register remote services to allow this Example Registry reg = LocateRegistry.getRegistry(); reg.bind("AirportDisplay",stub); Callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object. A utility program (rmiregistry) is used to build the registry.

Threads in Java

Monitors

Remote Method Invocation

A client

Example import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public static void main(String [] args) { try{ Registry reg = LocateRegistry.getRegistry(args[0]); HighLevelDisplay d = (HighLevelDisplay)reg.lookup("AirportDisplay"); ... d.addRow("hej");

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need the interface for the remote object to compile both the server class and the client class: In one machine:

In the other machine:

> javac HighLevelDisplay.java > javac JDisplay2.java

> javac HighLevelDisplay.java > javac Client.java

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need the interface for the remote object to compile both the server class and the client class: In one machine:

In the other machine:

> javac HighLevelDisplay.java > javac JDisplay2.java

> javac HighLevelDisplay.java > javac Client.java

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need the interface for the remote object to compile both the server class and the client class: In one machine:

In the other machine:

> javac HighLevelDisplay.java > javac JDisplay2.java

> javac HighLevelDisplay.java > javac Client.java

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need to start the rmiregistry before executing In one machine: > rmiregistry & > java JDisplay2

In the other machine: > java Client

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need to start the rmiregistry before executing In one machine: > rmiregistry & > java JDisplay2

In the other machine: > java Client

Threads in Java

Monitors

Remote Method Invocation

Compiling and Running

You need to start the rmiregistry before executing In one machine: > rmiregistry & > java JDisplay2

In the other machine: > java Client

Threads in Java

Monitors

Remote Method Invocation

The remote object should be a monitor!

The remote display will be accessed by several clients and a process is started to serve each remote method invocation. The implementation of the remote display must be done so that it is thread safe!

Related Documents

Lecture12
June 2020 2
Lecture12
October 2019 4
Lecture12
November 2019 4
Lecture12
June 2020 2
Lecture12
October 2019 3
Lecture12.pdf
June 2020 4