Andres Delrotti wrote:Most of us use Singletons as kind of a memory storage in the JVM. Usual case is the values of a singleton class are set during application startup then accessed later on. At some processes or functions in the application, we update its values.
Really? I don't think I've ever used a Singleton like that. Indeed, other than enums, I can't remember the last time I used one at all.
2. Does this mean we should always use synchronized methods when processing or changing values of singleton classes? shouldn't a synchronized getInstance method be able to handle that? im confused
If indeed you
do update your singleton (which sounds like a dubious practise to me to begin with), then if it
also needs to be Thread-safe, you need to write it just as you would any other Thread-safe object; there's nothing special about the fact that it's a singleton.
So, yes, that means that you need to use
synchronized and/or
volatile just as you would for any other Thread-safe class.
Winston