Alternatively, if they are static variables, though, then without the method being synchronized, the items are not safe from concurrent access in general. The only way they might be safe is if the methods to access these static variables are synchornized such as java.util.Hashtable.
will acquire the monitor for anObject. If another thread already has the monitor it will have to wait for that thread to finish before it can acquire it and proceed. Any piece of code that synchronizes on a common object will not be able to run concurrently since only one thread can acquire the monitor on that object at any given time. In the case of methods the monitor used is implicit. For non-static methods it's the instance it was called on, for static methods it's the Class for the type it's called on.
Originally posted by Edwin Dalorzo:
You use synchronized if your foresee that multiple threads may concurrently try alter the values of the any fields of you class.
That's one possible reason but it hardly constitutes an accurate indication of when to use the keyword.
To answer the question I would say you use synchronized whenever you don't want two threads concurrently executing a critical section based upon a common monitor. The situations in which you would need this are many and riddled with far too many gotchas and exceptions to explain fully.
Originally posted by dipali toshniwal:
synchronized is use only when u want that perticulat method/class can be access by only one thread
[ January 17, 2006: Message edited by: Bear Bibeault ]
You can't prevent access to an entire class with synchronized. You can make every method synchronized, but still that's not quite the same thing. Plus, it only prevents other threads from accessing the critical section when synchronized on the same monitor.