Question on Singleton?
hi,
class A {
private A a = new A();
public static A getInstance(){
return a;
class A {
private static volatile A _instance;
public static A getInstance(){
if(_instance == null){
synchronized(A.class){
if(_instance == null)
_instance = new A();
return _instance;
}By the two ways we can achieve Singleton, can anyone please explain the first one having any disadvantage over the second one?
1. It gets created even if no-one ever uses it.
2. It gets created during application load time rather than when first used, which makes for a worse user experience.
Similar Messages
-
Question about singleton design
Hi all
i have a question about singleton design. as i understood it correctly, this pattern garantees us a single instance of a class at any time. in a environment of concurrent access(multiple user access at the same time) , does this single instance put a constraint on concurrency(singleton == synchronization)? i have developed a service object that reads in properties and constructs some other objects. the reason i made it singleton is that i only want this service object to load the properties once. and when it is called to create other objects, it always has one copy of the propertis. making this service singleton, will it limit the threads to access it and construct other objects? thanks for your help.If there's no write access to the HashMap, then
you're thread safe.You were probably typing at the same time as the previous post, which explicitly says there IS write access to the HashMap.
I don't know what it is, but people seem to have this magical view of concepts. Singleton is just what it is. It doesn't have a magical aura that causes other things to behave differently. A singleton is just Java code that can have thread safety problems just like any other Java code. So to the OP: forget about the fact that this is a singleton. That's irrelevant. Ask if a method needs to be synchronized.
(And yes, a method that tests if a variable is null and assigns an object to it if it isn't null does need to be synchronized if it's going to have multiple threads accessing it.) -
Is abap thread safe? Some question in Singleton pattern in ABAP
Hi Grus,
I have a very basic question but really make me headache...
Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
Could you help me on the question? Thanks a lot, grus
And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
BR,
SteveSteve,
I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
Best regards. -
Interview question on singleton
Hi all,
I recently attended an interview and i left feeling like an idiot because of one of the questions I messed up with. I would like an answer to that question.
The question is: you have a singleton object in a POJO. The singleton is shared by many users accessing it, the first user that requests the singleton has to pay a penalty for initialising the singleton object i.e. the object has to connect to a database and retrieve some records (it takes up to 5 minutes to get this data out). How can you write the singleton class so that the first user of the object does not have to wait the data to load.
does anyone have any ideas on how to achieve this?
thanks in advance.My thought would be to avoid using lazy initialization for the singleton.
Initialize the singleton at application startup (class load time), thereby
taking the hit when starting the app, but only then.That however exceeds the bounds of the question.
The question asks "How can you write the singleton class ...."
Note as well that a POJO framework, specified in the question as well,
does not implicitly provide for an explicit class load
execution on startup.
Now perhaps the interviewer wanted the interviewee to exceed the
bounds of the question.
Or perhaps the interviewer wanted the answer that it
wasn't possible (or at least not realistic.)
Or perhaps the answer was to use threads and thus
delay, potentially, the wait to the actual data access rather
than the getInstance(). Although obviously that really
points to an interviewer that has no idea what the question
really entails. -
A question about singleton pattern
Will a singleton instance be a bottleneck of an application when many client address this instacne?
and How can I do to deal with this problem?
help me!Unless the singleton has synchronized methods or blocks of code that are synchronized there should be no bottle neck, as multi threads can access it at the same time.
-
Is singleton thread safe?
hello all,
please help me by answering these questions?
singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created
Can singletons be used in a multithreaded environment? is singleton thread safe?
Are threading problems a consequence of the pattern or programming language?
thank you very much,
HiruHi,
Before explaining whether a singleton is thread safe
e i want to explaing what is thread safe here
When multiple threads execute a single instance of a
program and therefore share memory, multiple threads
could possibly be attempting to read and write to the
same place in memory.If we have a multithreaded
program, we will have multiple threads processing the
same instance.What happens when Thread-A examines
instance variable x? Notice how Thread-B has just
incremented instance variable x. The problem here is
Thread-A has written to the instance variable x and
is not expecting that value to change unless Thread-A
explicitly does so. Unfortunately Thread-B is
thinking the same thing regarding itself; the only
problem is they share the same variable.
First method to make a program threadsafe-: Avoidance
To ensure we have our own unique variable instance
for each thread, we simply move the declaration of
the variable from within the class to within the
method using it. We have now changed our variable
from an instance variable to a local variable. The
difference is that, for each call to the method, a
new variable is created; therefore, each thread has
its own variable. Before, when the variable was an
instance variable, the variable was shared for all
threads processing that class instance. The following
thread-safe code has a subtle, yet important,
difference.
second defense:Partial synchronization
Thread synchronization is an important technique to
know, but not one you want to throw at a solution
unless required. Anytime you synchronize blocks of
code, you introduce bottlenecks into your system.
When you synchronize a code block, you tell the JVM
that only one thread may be within this synchronized
block of code at a given moment. If we run a
multithreaded application and a thread runs into a
synchronized code block being executed by another
thread, the second thread must wait until the first
thread exits that block.
It is important to accurately identify which code
block truly needs to be synchronized and to
synchronize as little as possible. In our example, we
assume that making our instance variable a local
variable is not an option.
Third Defence:--Whole synchronization
Here u should implement an interface which make the
whole class a thread safe on or synchronized
Thre views are made by Phillip Bridgham, M.S., is a
technologist for Comtech Integrated Systems.I'm
inspired by this and posting the same hereWas there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established. Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.
private Object lock;
public void doSomething() {
lock = new Object();
synchronized(lock) {
// Do something.
}It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.
This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.
It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere. -
Important: singleton questions...
While I was developing a program, I found there is a question bothering me alot. It is singleton question. For example, I created an object 1. when I was implementing another object, I thought I need to use object 1, so I instiated an instance. But when I was implementing third object, I accidently create another instance of object 1. Now problem has came, I have two instance for object 1.
What I really want is to only use one instanc of object!
In order to avoid conquering this confusing, I come out a conclusion. I think we can use two ways to make sure there exists only one object instance in the program.
one way is pass the object as parameter, like:
public void getTable( Properties configSettings);
another way is make a single class, this class will allow only one object instance exists.
implementation:
public class Singleton {
private static Singleton instance;
public Singleton getSingleton();
public Singleton() {
instance = null;
public Singleton getSingleton(){
if( instance ==0){
return instance = new Singleton;
Is this implementation right? It seems I missed sth?two things that dubwai already included in his code:
- make sure the constructor is not public (so new instances can't be created outside the class)
- provide a "getInstance(...)" method that will retrieve the one and only static instance...
class Singleton
private static Singleton instance = null;
protected Singleton( Object param )
// do something with param...
public Singleton getInstance( Object param )
if(instance == null)
instance = new Singleton(param);
return instance;
}Note that this has the potential confusion that the parameter sent in getInstance() is only used the first time its called.
It's recommended that you avoid the need for extra parameters in the singleton construction. If you only need one instance of the object then that's probably the case anyway (I can't think of a reason for params). -
Question: Justification of singleton implementation
Hi there,
I have a question here about using singleton design for process that serves lots of threads in a web application behind a servlet justifies? What sort of impact to the server will be even the implementation of singleton is not targeted on synchronization of I/O within the server?
Thanksjwenting wrote:
georgemc wrote:
original wrote:
yawmark wrote:
but servlets are all singletons. No, they aren't. Having only one instance of a class -- as is often the case with servlets -- is not the same thing as a Singleton.
is there a reason for this?No, because it isn't true. Stop trolling, daFei.
~i take it that you have no answers.Other than the ones he's given, of course. Silly boy
Steve, best add "a singleton is a class for which you've only created one instance" to the listAnd do remember to pass it around by reference!Heh heh -
Sort of singleton pattern , design question
Hi
i need to a class which has only one instance( can use a singleton pattern) but the problem is there have to be some variables to be initialised and this class will not know how to initialise them, how do i desin it
public class MyData
private String data;
private String data2;
private static MyData instance;
public MyData getInstance()
return instance;
public String doSomeThing(String parm3)
// but parm1 and parm2 are not initalised, they are common for all classes,
// how do i desing it
return parm1 + parm2 + parm3;
ashishhi
I know it is not a good desing , but my problem is
that my SingleTon pattern is sort of worker class,
which will be accessed from many other classes, these
classes also dont know the values of parm1 and parm2
required by the worker class,
these values are setup by the startup java class
which reads them from a properties file, this worker
class has no knowledge of this properties file and
hence cannot retrieve it...
so what are my optionsHave the singleton get the values itself from system properties, or a file or database or java.util.Preferences or some other appwide configuration.
Or do what DrC suggested and have a factory do that and let the factory push the values to the singleton.
, i dont want to make these
variables static since there will be problem in my
applicationAnd what problem would that be? -
Question about synchronized singleton classes
Hi,
I have a singleton class, with only 1 method (which is static), I want access to that method to be synchronized, but someone suggested that I make my getInstance() method synchronized as well.
Is this neccessary, or is it overkill?
thanks!Example:
static Instance getInstance() {
if (instance == null) {
instance = new Instance();
return instance;
}Two threads call it simultaneously:
1. if (instance == null) { // evaluates true
2. if (instance == null) { // evaluates true
1. instance = new Instance(); // first instance
2. instance = new Instance(); // second instance,
deleting the reference to the first instance
1. return instance; // which is not the originally
created one but the second instance
2. return instance;There's actually a worse consequence.
1) T1 sees null
2) T1 sets instance to point to where the object will live
4) T2 sees non-null
3) T2 returns, with a pointer to what's supposed to be an object, but isn't yet inited.
4) T1 eventually inits the instance
This can happen even if you use the "double check locking" pattern of synchronization.
At least under the old memory model. I think the new JMM in effect in 5.0 (and possibly later 1.4) versions fixes it. I don't know if the fact that it can happen in absence of sync/DCL is an error or not, so I'm not sure if that's addressed in the new JMM, or if it's only the synced case that was a bug. (That is, it might be okay that it happens without syncing.) -
Singletons and multithreading question
Hi, I had a class created as a singleton as it was only used in one place. However since Ive now multithreaded the part of the program that calls the singleton code so it could be called twice at the same time.
If the method being called initializes all its variables within the method, is that method safe to be called in a mutli-threaded env or not ?
If it in my situation all variables are declared within the method except a precompiled javax.xml.XPathExpression class, the same one is used to parse an Input Source, the input source itself is created within the method. I
think I am having concurrency problems , (SAXParser Exceptions) and I think it is because of this XPathExpression class but cannot clearly understand why.
What is the correct solution, I dont want to initilize the XPathExpression within the method because the method is called many times always for the same expression, dropping the singleton and creating new instances of the class on every call would be even worse. I require multithreading to improve concurrency is there a safe Multi Singleton pattern that i should be using ?There are two issues:
a) is the singleton object safe for multithreaded use
b) how do I safely create a singleton in a multi-threaded application
The answer to (a) depends on the class. It sounds from your description that you are using an object (the XPathExpression) that might not be thread-safe. I can't tell you if it is or not. Assuming it is not you either need to synchronize this method so that all threads will go through it (and use the expression) one at a time - which may defeat the purpose of multi-threading - or else you need a way to use multiple instances of these expressions in different threads. As I'm not familiar with these classes I can't tell you what you can and can't do concurrently.
There are a number of answers to (b). Construction via static initialization is the simplest and safest. If you want lazy initialization and the class that holds the reference to the singleton must be loaded even if the singleton isn't needed, then lookup the initialize-on-demand-holder-class idiom (see Josh Bloch's "Effective Java" item 48) -
Object Singleton Thread question
Thanks for taking a second to read this. Please consider the following.
class Single{
private static Single instance;
private Single(){}
public Single getInstance(){
if(instance == null) instance = new Single();
return Single;
public static kill(){
instance = null;
class Watch{
public DO_IT(){
Single S = Single.getInstance();
// Sys out here says
// Single.instance is live as is S
Single.kill();
// Sys out here says
// Single.instance is null
// BUT S is not null
}Can someone tell my why this happens (see comments if you missed it).
ThanksI'm sorry and don't mean to be dense but in teh case
of a singleton object, multiple callers to
getInstance() are insured to get the same object
right? No, they get copies of references to the same object
caller1s_instance ---+
|
|
+-----------+
caller2s_instance---| singleton |
+-----------+
If caller A calls a method on their version of
instancee the change will show up in caller B's
version right? Yes, because the references both point to the same object, and that object's methods may change its internal state, and both refs would see that.
So why does something nulling the
object not make it go away?Becuase you don't "null the object." You set the reference to null. Setting one reference to null does not affect the object that referenc refers to, and does not affect other references to that object. Simliarly having caller1 set its instance to new Singleton() (thus violoating the singleton pattern, but that's not the issue here), you'd have two Singleton objects, and changing caller1 to point to the new one wouldn't affect the original object or caller1's reference.
caller1s_instance---null
+-----------+
caller2s_instance---| singleton |
+-----------+
Instance is RescU.RescU_Main@92d342
MyVersion is RescU.RescU_Main@92d342
After calling kill() they are
Instance is null
MyVersion is RescU.RescU_Main@92d342I hope the above explains this. If not let me know. -
Hi,
I need to create a class wherein most of the attributes like Queue Name, DB Name, JMS Connection, etc are static. The only thing variable is the actual message that i will be publishing to the queue. I am thinking to make this a Singleton class and initialize all the static attributes in the constructor and provide a setter/getter method of the message. Does this sound like an appropriate design?
Please let me know. Thanks!
JaKjakSun8 wrote:
Hi,
I need to create a class wherein most of the attributes like Queue Name, DB Name, JMS Connection, etc are static. The only thing variable is the actual message that i will be publishing to the queue. I am thinking to make this a Singleton class and initialize all the static attributes in the constructor and provide a setter/getter method of the message. Does this sound like an appropriate design?
Please let me know. Thanks!
JaKWhy are these variables to be static? ... do you want all Objects to NOT have their own copies of them? Do you want one Object to be able to alter any or all of them and thereby affect them for all other Objects accessing them? Or do you plan never to have more than one Object utilize them any time the process runs? Just curious is all. -
Hi,
I've developed queue, but would need some help in creating instances. The problem is each group has a queue for itself. The basic functionality is the same for the queues but it is group specific. At any given time I want only once instance of the queue for a particular group. And also, if the queue instance is does not exist it should be instantiated when the first time a it is tried to be accessed.
To make the long story short, I want to be able to create instances (only one for each group) from one parent class. Please help. Thanks.
ManjuNot sure I understand the question exactly - but would something like this do the trick?
public class Queue {
/** hashtable holding already-existing Q's, keyed by group-name */
static Hashtable _groupHash = new Hashtable();
/** Protected constructor to force use of factory method */
protected Queue ( ) {/*whatever the constructor needs to do here...*/ }
/** Factory method for constructing Queues for Groups */
public static Queue createQueueForGroup ( String groupName ) {
Object obj = _grouphash.get(groupName);
if (obj == null) { // No Queue - create the first one
Queue q = new Queue();
_groupHash.put(groupName, q);
return q;
} else { // return the already-created group-Q
return (Queue)obj;
}Factory is definately the design pattern to use when you want to impose limits such as the one you describe... -
Hello,
Could someone please explain what the following code does? How does it work? How can I use it in the real program?
More importantly, if you are kind enough, please give me some examples how to use singleton class? Why do we have to use this class?
I spent two days on this topic, Singleton, but my mind still goes blank.....
thank you.
public class Singleton
static public Singleton getInstance()
if(theInstance == null)
theInstance = new Singleton();
return theInstance;
protected Singleton()
//initializing instance fields
//instance fields and methods
private static Singleton theInstance = null;Hello,
Could someone please explain what the following code
does? The code defines a class called Singleton. :)
How does it work? The static method "getInstance()" returns an object of type Singleton. Static methods can be called without having an instance of a class, so you can type:
Singleton.getInstance();
How can I use it in the
real program?This class is pretty useless in a real program. The point of this class is to show you how the Singleton design pattern can be implemented in Java. Any useful Singleton object needs to have additional properties and methods. (Oh I know someone will say that you can still use this class for something, but I'm trying to explain something here...)
More importantly, if you are kind enough, please give
me some examples how to use singleton class? Sure, here's an example of a singleton: Suppose you want a debugging class that will simply write text to a file. You want to only have one instance of this class (i.e. you don't want to have multiple log files, you want to provide one single interface point for this):
class LoggerSingleton
private static final String LOGFILENAME = "log.txt";
private BufferedWriter write = null;
private LoggerSingleton instance;
synchronized static public LoggerSingleton getInstance()
{ if(instance == null) instance = new LoggerSingleton(LOGFILENAME);
return instance;
protected LoggerSingleton(String filename)
try {
write = new BufferedWriter(new FileWriter(filename));
write.write("Log File Opened");
write.newLine();
write.flush();
catch(IOException ioe)
System.err.println("Error! LoggerSingleton could not be initialized");
ioe.printStackTrace(System.err);
System.exit(1);
public log(String text)
write.write(text);
write.newLine();
write.flush();
}This class will make sure you only have one log file and ensures that all classes are using it:
class FirstClass {
SecondClass second = new SecondClass();
public FirstClass() {
LoggerSingleton.getInstance().log("Inside FirstClass' constructor");
public void func1() {
LoggerSingleton.getInstance().log("Inside FirstClass.func1()");
class SecondClass {
public SecondClass() {
LoggerSingleton.getInstance().log("Inside SecondClass' constructor");
Why do we have to use this class?You don't have to use this class, but it is one technique to ensure that multiple instances of an object are not instantiated. It is also a technique to ensure that there is only one interface point across the application (you can also use a Singleton object to implement the Bridge and Factory design patterns). The Singleton technique is achieved by making the constructor protected, which means that only methods inside the class (and package) can construct instances of Singleton. The only time an instance of Singleton is constructed is the first time that getInstance() is called.
I spent two days on this topic, Singleton, but my mind
still goes blank.....
Still blank?
Maybe you are looking for
-
IPOD NANO-Windows delayed write failed...
I just bought an IPOD NANO 4gb yesterday... Downloaded ITunes and have been having problems getting it to SYNC music to my IPOD. It keeps throwing the "windows delayed write failed" error. No other errors present. I havent been able to get any music
-
Hi Group: In trying to set up an ext Drive for different purpose, I cloned my Macintosh H.D. drive and saved on another drive. Then I cloned the data on the Ext, used my orig. DVD to install sy on it, 4 attempts before it would accept the install. Di
-
How do I determine if the Firefox I am running is 32 bit or 64bit?
I downloaded the latest version of Firefox (6.0.2). After the installation the wizard notified me that my Flash Player was out of date. I attempted to download the latest Flash Player and it told me it timed out and sent me to a trouble page. It said
-
Is there another way to open a different iPhoto library?
Is there another way to open a different iPhoto library besides using the option key and clicking on the iPhoto icon? It takes me upwards of a dozen times to get it to work, so I get that screen where I choose which library I want to open - the optio
-
EDGE Animations not working in inDesign
When I create a number of animations and export them as sepearte animations, and then take them into my inDesign project and place them as articles in my Folio, they either don't work and /or are very sluggish. Also in one of the EDGE animations I h