DEVFYI - Developer Resource - FYI

This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?

Java Interview Questions and Answers (part 1)


(Continued from previous question...)

143. This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?

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; 
    } 
} 

(Continued on next question...)

Other Interview Questions