Download presentation
Presentation is loading. Please wait.
1
COEN346 Tutorial Monitor Objects
2
Context Object with multiple features that require a certain type of synchronization Reader/writer example Object can allow multiple readers at the same time One writer at a time Either a writer or one or more readers Read and write are the features of the object
3
Trivial solution One can implement the synchronization in the reader and writer threads Hard to implement such synchronization Too many objects to pass to the threads for synchronization purposes (mutexs, conditions and semaphores used to synchronize each kind of threads) Execution overhead, no flexibility
4
Monitor Object Synchronized feature can only be accessed by one thread at a time Use lock and condition objects to control the access to critical section blocks The monitor object can implement its own scheduling algorithm to control the access to its own features (time sharing for instance) Object Monitor Object Thread_1 using feature_1 Feature_1 Feature_2 Feature_3 …. Synchronized Feature_1 Synchronized Feature_2 Synchronized Feature_3 …. Thread_2 using feature_1 Thread_3 using feature_2 Thread_4 using feature_3
5
Drawbacks, Any ?! Synchronization is tightly coupled with the logic of the features of the monitor object Useful for small number of features (because there is probably one way to synchronize them, and even if there is not reusing and customizing the synchronization code is not very hard) With large number of features it is better to use the active object pattern Decouples scheduling from the business logic Allows reusability as the scheduling can be customized See last slide of the first tutorial
6
Implementations Using semaphores implementations
The synchronization is not in the consumer side but in the handler side
7
import java. util. concurrent. locks. Lock; import java. util
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; Public class ReaderWriterMonitor { private final Lock mylock = new ReentrantLock(); private final maxCapacity = max_allowed_Readers_at_a_time; private final Lock counterLock = new ReentrantLock(); private int readerCount = 0; private final Condition canread = mylock.newCondition(); public void write(){ mylock.lock(); //write here mylock.unlock(); } public void read(){ counterLock.lock(); if(readerCount==0) mylock.lock(); if(readerCount==maxCapacity){ counterLock.unlock(); canread.await(); readerCount++; //do the reading here readerCount--; canread.signal(); }else{ If(readerCount==0) mylock.unlock(); }} Public class ReaderRunnable implements Runnable{ @override public void run(){ ReaderWriterMonitor rwm = new ReaderWriterMonitor(); rwm.read(); } Public class WriterRunnable implements Runnable{ rwm.write();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.