Adobe Interview Question
Software Engineer / DevelopersSemaphore is having protected non-negative integer value, which control critical section execution by process/threads.
With the below implementation we can control any critical section by issuing with below sequences..
WAIT();
// Start Critical Section...
... do whatever you want to carry out....
// End Critical Section...
SIGNAL();
public void SemaPhore {
private int mutex = 1;
public synchronized WAIT() {
while(mutex == 0) {
try {
wait(); // wait till other thread/process notifies it to proceed.
} catch(InterruptedException e) {
// keep trying...
}
}
mutex--;
}
public synchronized SIGNAL() {
mutex++;
notifyAll(); // notify all the thread
}
}
In java concurrent access is managed by synchronized methods or statements.
This question is to test the same...
solution:
//making member static so that synchronization is for class rather than individual instance.
//
private static counter = 0;
public synchronized static void increase(){
counter++;
}
public synchronized static void decrease(){
if(counter > 0)
counter--;
}
//
// java concurrency mechanism takes care of notifying all the other threads who are waiting to gain the access.
public class Semaphore {
- random May 10, 2009private final int MAX_SLOTS = 10;
private int empty_slots = MAX_SLOTS;
public void down() {
synchronized (this) {
while (empty_slots == 0) {
try {
wait();
} catch (InterruptedException ex) {
}
}
empty_slots--;
}
}
public void up() {
synchronized (this) {
if (empty_slots < MAX_SLOTS) {
empty_slots++;
}
notifyAll();
}
}
}