Vaibhav Gargs wrote:... but as per synchronized context, other threads won't be able to access.
This is not true. You can access variables just fine, even if they're used inside a synchronized context. You just can't enter a synchronized context by two different threads at the same time if they use the same lock. Here's an example of a volatile variable being used in conjunction with a synchronized block:
Even though cancelled is being used in a synchronized context in the
run() method, it's not in a synchronized context in the
cancel() method. We could make the
cancel() method synchronize on
model as well, but that would be overkill because the assignment is already an atomic operation. We do need to make
cancelled volatile though, so the
run() method picks up its latest value immediately. All of this would work the same if
cancelled was static, but then you would cancel ALL instances of
SomeTask.
There's little reason to ever make a static variable volatile. After all, your application should not have globally accessible state.