Question - This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?
Answer -
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}
The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}