Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
since the method1 and method2 are synchronized, I don't think they will run in to a race condition. Because, it is not possible for two invocations of synchronized methods on same object to interleave.
correct me if I am wrong?
When you use synchronized method for static method you get lock on the class and not on class object. So in the above example you have two separate locks. On the the class and other on its object. No one blocks the other one and hence the race condition can happen.
Solution: Either use 2 variables or change static method to non-static.
import java.util.concurrent.atomic.AtomicInteger;
- rajeshrp21 April 21, 2012public class TrackCount {
private static AtomicInteger count = new AtomicInteger(0);
static synchronized void method1()
{
count.incrementAndGet();
}
synchronized void method2()
{
count.incrementAndGet();
}
}