Code snippet - 1
class RequestObject implements Runnable
{
private static Integer nRequests = 0;
@Override
public void run()
{
synchronized (nRequests)
{
nRequests++;
}
}
}
Code snippet - 2
class RequestObject implements Runnable
{
private static Integer nRequests = 0;
private static Object lock = new Object();
@Override
public void run()
{
synchronized (lock)
{
nRequests++;
}
}
}
While the second code snippet is working fine without causing any race conditions, the first one isn't successful in synchronizing access to the static data member between different instances of the same class(RequestObject). Could somebody throw more light on this. I would like to understand why the first approach isn't working.
My original implementation is the first one. The later I saw in https://stackoverflow.com/a/2120409/134387.