what are the problems of the snippet
my purpose is to implement a counting semaphore (one concurrency control object) in java. (I know it is available in java.util.concurrent, but this is the requirement).
Here is the code:
Code:
public class countingSemaphore{
private static final int _MOSTTABLES = 3;
private static int availtable = _MOSTTABLES;
private static final Object lock = new Object();
public synchronized static void Wait(){
while(availtable==0){
try{
synchronized(lock){
lock.wait();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
}
availtable--;
}
public synchronized static void Signal(){
while(availtable==_MOSTTABLES){
try{
synchronized(lock){
lock.notifyAll();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
}
availtable++;
}
}
The synchronized static methods lock resource sharing among instances of class. The synchronized within methods is to use wait/notifyall mechanism for a static level method.
But these codes still look strange though I do not figure out the strange reason.
Can anybody tell me why? Or any other issues I have to take care of here in order to implement the counting semaphore. Thanks.