I don’t understand what is wrong with this code. Sometimes two threads start executing the try block. I am creating a new instance of popo every time I call the function. Can please anybody figure out what the problem is?
public class Instance {
private static AtomicInteger i = new AtomicInteger(0);
public synchronized void incrementInstance() {
i.getAndIncrement();
}
public synchronized void decrementInstance() {
i.getAndDecrement();
}
public synchronized int getInstances() {
return i.get();
}
}
public class popo {
private static volatile MyMutex instanceMutex = new MyMutex();
public void doSomething() {
synchronized (instanceMutex) {
final Instance no = new Instance();
if (no.getInstances() > 0) {
instanceMutex.wait();
} else {
no.incrementInstance();
}
}
try {
// do something
} finally {
synchronized (instanceMutex) {
final Instance no = new Instance();
if (no.Instances() > 0) {
no.decrementInstance();
}
instanceMutex.notify();
}
}
}
private static class MyMutex {}
}
I think the code smells all over the place 🙂 Actually, doing things like creating new instances that do nothing more than access a static field make things confusing (see previous responses). So, this is what I suggest:
Then you can use the method getQueueLength() to know how many threads are waiting and replace the AtomicInteger you are using. See http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html