In chapter 9 of
SCJP study guide published by McGrawHill, on P.741, it mentions "Or a static method that access a non-static field (using an instance)?"
The paragraph was talking about modifying a non-static field of a class via a synchronized static method. The class object is locked. But there is another
thread running another synchronized non-static method trying to modifying the same non-static field. Since synchronized static and non-static methods are not blocking each other, they may modify the same non-static field at the same time, which is not thread safe.
But the issue is a synchronized static method cannot access a non-static field.
For example,
class MyRunnable implements Runnable{
private int a = 0;
public void static access(){
a = 100; // compile error: cannot make a static reference to a non-static field
}
}
But if this case:
class MyRunnable implements Runnable{
public void static access(){
AnyObject any = new AnyObject(); //assume there is a class AnyObject and there is an integer aNumber inside it.
any.aNumber = 100; // This any object is a local copy of the access method. Two threads have their own local copy. The modification won't affect each other.
}
}
So, please explain why "a static method that access a non-static field (using an instance)?" A static method accessing a non static field won't even compile.
Thanks.