first of all I am very new here, so I hope I will do all things right during questioning.
Your question is asked well so you got at least that right :)
4 other objects (the 4 threads) alternately try to leave() or enter()the Store object I will get an endless loop
When one thread enters the synchronized block, you are declaring that no other threads can enter a synchronized region of the same object until the thread has left the initial synchronized block. What you have is a thread invoking enter
and spinning until size is 0. For that to happen, size needs to be incremented, which cannot happen because another thread cannot invoke leave
(while the other thread is spinning for ever).
Solution
Instead of busy spinning ( while(<some condition>){ }
), have the thread wait
on the monitor. This will give up the lock so another thread can enter. And after leave
ing, notify any waiting threads.
public synchronized void leave(){
this.size++;
this.notify();
}
public synchronized void enter(){
while(this.size==0){
this.wait();
}
this.size--;
}