If I have a static method, and I create all my variables w/in the method, do I need to synchronize the method? or is it enough that the variables have been created inside of the method to keep it safe.
By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Depends what type of variables you are referring to. If they are local variables, then creating them inside the method is fine since the scope of local variables is never beyond the method.
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.
The synchronized keyword simply acquires the monitor for some object. For example:
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.
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 ]
posted 14 years ago
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.