I have code similar to following:
class OuterClass
{
private final AtomicInteger count = new AtomicInteger(0);
private class InnerClass extends TimerTask
{
public void run()
{
......
......
incremenetCount();
}
}
public void doSomething()
{
.......
.......
incremenetCount();
}
private void incrementCount()
{
count.incrementAndGet();
}
}
Is calling incrementCount from inner class the same as calling it from any other function in outer class as the synchronization is actually around the variable count?
Yes, calling
incrementCount()from the inner class is the same as callingincrementCount()from the outer count.All non-static inner classes have an implicit reference to the object of the enclosing class, and it is through this reference the
incrementCount()will be called.(Story would have been different if your inner class was static though.)
Doesn’t matter. The same method, is called on the same object, regardless if you do the call from the inner or from the outer class.