Amazon Interview Question
Software Engineer / DevelopersThe above code gets into a deadlock when the counter is more than the bound value since it does not release the lock.
I did not understand your point here.
Suppose bound value is 5.
So now thread1, thread2, thread3, thread4, thread5 will call isSafe and increment counter to 5. now if 2 more threads thread6, thread7 calls it, they will be in continuous while loop until any of 1 to 5 threads call notifyDone().
The flaw in this code can be that Semaphore class should be singleton.
here is the implementation of counting semaphores.
public class CountingSemaphores {
private int signals = 0;
private int upperBound = 0;
public CountingSemaphores(int upperBound) {
this.upperBound = upperBound;
}
public synchronized void take() throws InterruptedException {
while(signals == upperBound) {
wait();
}
signals++;
this.notify();
}
public synchronized void release() throws InterruptedException {
while(signals == 0) {
wait();
}
this.signals--;
this.notify();
}
}
Now simply create one object of this CountingSemaphores class and use take and release methods for synchronizations.
CountingSemaphores countingSemaphore = new CountingSemaphores(10);
Task1 t1 = new Task1(countingSemaphore);
Task2 t2 = new Task2(countingSemaphore);
t1.start();
t2.start();
In run methods of task1 call take method of CountingSemaphores class and in run method of task2 call release method of CountingSemaphores class.
Thats it I hope this will help.
Correct me if I am wrong or any modification required in code.
Thanks
This was the only question asked to me for 45min phone interview. Interviewer had shared etherpad where I was suppose to write the code. I came up with below code which I thought was not good enough because he asked me a major flaw in this code. So I realized that it has unnecessary high CPU utilization. So he asked me how would you remove that(not implementation). At that time could think of only putting sleep (after the interview I realized wait-notify would have been better, but anyways time was gone).
But I got my third interview call, so I guess he just judged my thinking process. :)
Here is that (no so good)code:-
- Mugdha February 02, 2011