In formal terms, a monitor is an object which only allows one of its methods to
ID: 3802375 • Letter: I
Question
In formal terms, a monitor is an object which only allows one of its methods to be executed at once.
For Java:
1) How could you implement a class satisfying the monitor’s fundamental mutual exclusion property – that is, a class whose instantiated objects ensured mutual exclusion among their methods? Provide a code fragment as an example.
2) Could you mutually exclude critical sections smaller than an entire method without resorting to mutex locks? If so, how?
3) How would you implement condition variables as we described them in class? Provide a code fragment as an example.
4) Does the implementation differ if you need more than one condition variable? If so, how?
Explanation / Answer
Q1 implementing a class satisfying the monitor’s fundamental mutual exclusion property is by synchronized in java
we can write synchronized function
public synchronized void funcA(Object a ){
// code of the function
}
so if two thread access at same time only one thread will be able to execute it and other thread will wait
Q2 java also provide synchronized blocks
eg void funcA(object a)
{
synchronized(a){
// critical section of the code
}
}
Q3 to implement condition variable
public synchronized void func(object a)
{
// here we want to wait untill the value of any condition variable is false
whiile(isval == true)
{
a.wait();
}
}
in the above code our code will not execute and will be in waiting state untill the value of the variable isval is true;
Q4 the implementation will differ if there are multiple condition variable.
then there will be more condition which are to be checked in our code