Vous êtes sur la page 1sur 109

Threads in Java Monitors Remote Method Invocation

Embedded Systems Programming


Lecture 12

Verónica Gaspes
www2.hh.se/staff/vero

Center for Research on Embedded Systems


School of Information Science, Computer and Electrical Engineering
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 { class T2 extends Thread {


public void run(){...} 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 { class T2 extends Thread {


public void run(){...} 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 { class T2 extends Thread {


public void run(){...} 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 { class T2 extends Thread {


public void run(){...} public void run(){...}
} }
Threads in Java Monitors Remote Method Invocation

Monitors in the real world . . . Lizards


Threads in Java Monitors Remote Method Invocation

Monitors in the real world . . . Screens


Threads in Java Monitors Remote Method Invocation

Monitors in the real world . . . Submarines


Threads in Java Monitors Remote Method Invocation

Monitors in programming languages . . .


A language approach to synchronization
Threads in Java Monitors Remote Method Invocation

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;
}
}
Threads in Java Monitors Remote Method Invocation

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;
}
}
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
Example
the integrity of the
representation! void main(String args[]){
Counter cnt = new Counter();
Thread [] turns = new Thread[10];
Only one thread at a
for(int i = 0; i<10;i++){
time is allowed to be
turns[i] = new CounterUser(cnt);
using the monitor.
turns[i].start();
}
All other threads are }
blocked until they can
be given permission to
enter.
Threads in Java Monitors Remote Method Invocation

What does this mean?

The abstract data type


can be shared by many
threads while preserving
Example
the integrity of the
representation! void main(String args[]){
Counter cnt = new Counter();
Thread [] turns = new Thread[10];
Only one thread at a
for(int i = 0; i<10;i++){
time is allowed to be
turns[i] = new CounterUser(cnt);
using the monitor.
turns[i].start();
}
All other threads are }
blocked until they can
be given permission to
enter.
Threads in Java Monitors Remote Method Invocation

What does this mean?

The abstract data type


can be shared by many
threads while preserving
Example
the integrity of the
representation! void main(String args[]){
Counter cnt = new Counter();
Thread [] turns = new Thread[10];
Only one thread at a
for(int i = 0; i<10;i++){
time is allowed to be
turns[i] = new CounterUser(cnt);
using the monitor.
turns[i].start();
}
All other threads are }
blocked until they can
be given permission to
enter.
Threads in Java Monitors Remote Method Invocation

What does this mean?

The abstract data type


can be shared by many
threads while preserving
Example
the integrity of the
representation! void main(String args[]){
Counter cnt = new Counter();
Thread [] turns = new Thread[10];
Only one thread at a
for(int i = 0; i<10;i++){
time is allowed to be
turns[i] = new CounterUser(cnt);
using the monitor.
turns[i].start();
}
All other threads are }
blocked until they can
be given permission to
enter.
Threads in Java Monitors Remote Method Invocation

What does this mean?

The abstract data type


can be shared by many
threads while preserving
Example
the integrity of the
representation! void main(String args[]){
Counter cnt = new Counter();
Thread [] turns = new Thread[10];
Only one thread at a
for(int i = 0; i<10;i++){
time is allowed to be
turns[i] = new CounterUser(cnt);
using the monitor.
turns[i].start();
}
All other threads are }
blocked until they can
be given permission to
enter.
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 Monitors Remote Method Invocation

What we don’t see ...


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<T>{
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
private int count = 0;
private int n;
private T[] buf;
private int front = 0;
private int rear = 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<T>{
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
private int count = 0;
private int n;
private T[] buf;
private int front = 0;
private int rear = 0;
...}
Threads in Java Monitors Remote Method Invocation

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(); }
}
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 Remote Method Invocation

Organizing the program in Java

import java.util.concurrent.locks.*;
class RWScheduler{
public void requestRead()
public void requestWrite()
public void releaseRead()
public void releaseWrite()
}
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 int nr = 0;
private int nw = 0;
private int dr = 0;
private int dw = 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 Remote Method Invocation

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();}
}
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 Remote Method Invocation

An object will be shared by many threads . . .

Example
class BoundedBuffer<T>{
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(){...}
}
Threads in Java Monitors Remote Method Invocation

Make it thread safe (make it a monitor!)


Example
import java.util.concurrent.locks.*;
class BoundedBuffer<T>{
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 Remote Method Invocation

Now many threads can use it concurrently . . .

Example
public static void main(String[] args){
BoundedBuffer<Integer> theBuffer =
new BoundedBuffer<Integer>(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();
}
}
Threads in Java Monitors Remote Method Invocation

Now many threads can use it concurrently . . .

Example
class Producer extends Thread{
private BoundedBuffer<Integer> bb;
private int id;
private Random random = new Random();
public Producer(BoundedBuffer<Integer> 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 There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
Threads in Java Monitors Remote Method Invocation

What happens to the threads?

In a concurrent program, many


threads will be making progress There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
Threads in Java Monitors Remote Method Invocation

What happens to the threads?

In a concurrent program, many


threads will be making progress There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
Threads in Java Monitors Remote Method Invocation

What happens to the threads?

In a concurrent program, many


threads will be making progress There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
Threads in Java Monitors Remote Method Invocation

What happens to the threads?

In a concurrent program, many


threads will be making progress There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
Threads in Java Monitors Remote Method Invocation

What happens to the threads?

In a concurrent program, many


threads will be making progress There is also an explicit way of
simultaneously. putting threads to sleep, namely
the method await on a condition
variable!
If many threads share an instance
of BoundedBuffer, only one will
And a way of explicitely waking a
get to execute fetch or deposit
thread, namely the method
at a time! (they appear to be
signal on a condition variable.
atomic!)
Who does a signal?
And the other threads?
Another thread that when
They are put to sleep waiting for
running discovers that it has
permission to run the method
made some condition valid!
they want!
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
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 A remote server object is put to


some background threads and work by
offering some methods is defined
1 Creating an instance using a
in two stages:
constructor.
1 An interface declares the
2 Installing it as a remote
methods that can be called
object on a port.
from other virtual machines,
3 Binding a name to this
2 A class implements this
object at its port.
interface
Threads in Java Monitors Remote Method Invocation

An airport display

Example
A client process running on the
computer of the airline operator
can
Example
A display showing the arrival or add an info line by calling
departure times of aircraft at an addRow
airport. It can be used by all the remove an info line by calling
airlines to publish info about their deleteRow
flights. 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
Example A client process running on the
A display showing the arrival or computer of the airline operator
departure times of aircraft at an can
airport. It can be used by all the
add an info line by calling
airlines to publish info about their
addRow
flights.
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
Example A client process running on the
A display showing the arrival or computer of the airline operator
departure times of aircraft at an can
airport. It can be used by all the
add an info line by calling
airlines to publish info about their
addRow
flights.
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
Example A client process running on the
A display showing the arrival or computer of the airline operator
departure times of aircraft at an can
airport. It can be used by all the
add an info line by calling
airlines to publish info about their
addRow
flights.
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
Example A client process running on the
A display showing the arrival or computer of the airline operator
departure times of aircraft at an can
airport. It can be used by all the
add an info line by calling
airlines to publish info about their
addRow
flights.
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
Example A client process running on the
A display showing the arrival or computer of the airline operator
departure times of aircraft at an can
airport. It can be used by all the
add an info line by calling
airlines to publish info about their
addRow
flights.
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 HighLevelDisplay.java


> javac JDisplay2.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 HighLevelDisplay.java


> javac JDisplay2.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 HighLevelDisplay.java


> javac JDisplay2.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:
In the other machine:
> rmiregistry &
> java Client
> java JDisplay2
Threads in Java Monitors Remote Method Invocation

Compiling and Running

You need to start the rmiregistry before executing

In one machine:
In the other machine:
> rmiregistry &
> java Client
> java JDisplay2
Threads in Java Monitors Remote Method Invocation

Compiling and Running

You need to start the rmiregistry before executing

In one machine:
In the other machine:
> rmiregistry &
> java Client
> java JDisplay2
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!

Vous aimerez peut-être aussi