Does Java monitor include instance variables?
Yes. Holding the monitor of an object prevents another thread from executing another block of code or synchronized on the same object. If a method is not synchronized, any thread can call it at any time, whether another thread holds a monitor or not.
Every access to a shared stated, even read-only accessed, must be synchronized if there's a chance that at least one thread modifies this shared state.
Is it that monitor in java does not restrict access to instance variables and only to the methods which are declared synchronized or code in synchronized statements?
Yes.
Synchronized blocks (or methods) are, among other things, mutually exclusive. That does not prevent the object used as a lock (the monitor, let's call it lock
) to be used outside those blocks, in which case no synchronization will be performed. For example, one thread could read or write lock
while another thread is within a synchronized block where lock
is the monitor.
If you want to restrict access to a variable, you need to make sure that all accesses are made while holding a lock (any lock, provided it is the same for each access).