even a singleton object may be accessed simultaneously by multiple threads. You still have to take care of correct synchronization if you want to make access to it thread-safe. And there are subtle difficulties to create a real singleton in a multi-threaded application. You can't just use the typical singleton pattern if you want to guarantee that there will be really only one instance of this class. You'll find lots of discussions on this on the internet. There's a typical pattern called double-checked locking which still leaves the possibility that more than one instance of a class will be created. You'll find a correct solution in Brian Goetz's book but it's too complicated to explain all this here in short.
Originally posted by jacob deiter: singleton means one instance in the entire application,so a singleton class can be multithreaded?
Actually, this is not true. Google for "singleton considered stupid" for details. The Singleton pattern was made famous by the gang of four book, but it not nearly as simple, or as useful, as they indicate.
The problem is your phrase "entire application". In complex webservices, there may be more than one class loader, and this can cause there to be more than one loaded instance of your "singleton" which really means its not a singleton.
It is also a serious restriction on later "re-use" of your code if you don't make it thread safe. As any code that uses your code will become unsafe if your code is unsafe.
Today, 4 processor CPUs are cheap. Soon there will be 16 and 32 processor cheap systems.
That's mostly true, Amit. Some custom classloaders (like in Tomcat) may load code from their own classpath before their parents', and OSGI doesn't really arrange its custom classloaders in a tree at all.
It is true for most desktop and JEE applications, though.
crispy bacon. crispy tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop