However—what if you have a non-static method that accesses a static field?
Or a static method that accesses a non-static field (using an instance)? In
these cases things start to get messy quickly, and there's a very good chance that
things will not work the way you want. If you've got a static method accessing a
non-static field, and you synchronize the method, you acquire a lock on the Class
object. But what if there's another method that also accesses the non-static field,
this time using a non-static method? It probably synchronizes on the current
instance (this) instead. Remember that a static synchronized method and a
non-static synchronized method will not block each other—they can run at
the same time. Similarly, if you access a static field using a non-static method,
two threads might invoke that method using two different this instances. Which
means they won't block each other, because they use different locks. Which means
two threads are simultaneously accessing the same static field—exactly the sort of
thing we're trying to prevent.
It gets very confusing trying to imagine all the weird things that can happen here.
To keep things simple: in order to make a class thread-safe, methods that access
changeable fields need to be synchronized.
Access to static fields should be done from static synchronized methods. Access
to non-static fields should be done from non-static synchronized methods.
Why we have to fallow this ifade
"Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronized methods."