Adobe Interview Question
Computer ScientistsCountry: United States
I Agree with your explanation. But It will be random behavior.
Sometime it will work some time it will crash or sometime it will be in infinite waiting.
Issue:
wait() will not work.
Root Cause: :
wait() (and notify()) work on resources\objects not on threads. But in this piece of code you are calling wait() on this (thread instance) not on object\resource.
Solution:
In place of static int variable use a Object as a lock:
private static final Object lock = new Object();
wait() -> lock.wait();
synchronized (lock) {
lock.wait(); // It's already locked so wait(sleep) till someone wakes me up
try{
/* Critical Section - Increment g */
}finally{
lock.notify();
}
}
first problem:
if one of the thread dies without unlocking no one can lock the resource again.
Second problem:
Only one thread can lock the resource at any point of time. Something like binary semaphore even on a multiprocessor system i.e. this code doesn't utilizes the mutlicore architecture.
As of now i can see only these two but i am sure there are many more.
To be precise, answer should be "it may work sometime and fail sometime"
Explanation:-
We have two processes P1 and P2, and lock=0;
if (lock) ---- Line 1
wait(); // It's already locked so wait(sleep) till someone wakes me up --- Line2
else ------ Line 3
lock=1; // I locked it ------ Line 4
/* Critical Section - Increment g */
lock = 0; // Lock released, so wakeup only one of other waiting threads, if any
Let's say P1 is scheduled first, and it execute Line1, and context switched with P2, and again P2 executes Line1, now we arrived to the condition where both P1 and P2 see lock as free, and will execute Line4, and as a result there will be deadlock as both will wait for lock to be freed but none would be able to do so.
Above piece of code will not work on any system. following is the reason:
- ansh04 August 30, 2014-> Single Processor : Lets assume Thread1 executes first line and found that "lock = 0" so it will go in to else condition. Before executing "lock =1" statement task switching takes place and another thread2 also found that "lock = 0". Thus at the same time 2 threads are in their critical section.
-> Multiprocessor system : Assume that 2 threads are executing same piece of code in parallel and both of them found that "lock =0" so both threads will enter into critical section.
Thus above code will not work on any system.