Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"POTENTIAL PROBLEM" in following prg ?

 
omkar patkar
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.Identify the problem within this snippet of Java/C# code. (This is not a trick question � there is a potential real problem in using this code)
class Singleton
{
public static Singleton Instance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}


this was an interview q asked to one of my freinds ........any one knows ?
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's an interview question, then let's put it in Jobs Discussion.
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Instance() method needs to be synchronized.

A small optimization tip would be to avoid the explicit initialization to null as in

private static Singleton _instance = null;

cuz the JVM will automatically take care of that.

Origina
lly posted by omkar patkar:
1.Identify the problem within this snippet of Java/C# code. (This is not a trick question � there is a potential real problem in using this code)
class Singleton
{
public static Singleton Instance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}


this was an interview q asked to one of my freinds ........any one knows ?
 
Shiv Sidhaarth
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Singleton
{
public static Singleton Instance() {
if (_instance == null)
synchronized
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}

The above should solve the problem

sankar
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
even better...I agree with that...

Originally posted by sankar sv:
class Singleton
{
public static Singleton Instance() {
if (_instance == null)
synchronized
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}

The above should solve the problem

sankar
 
Eric Lemaitre
Ranch Hand
Posts: 538
Eclipse IDE Hibernate Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi omkar !

this was an interview q asked to one of my freinds ........any one knows ?

It must be the multithread access issue, it is described in HFDP (Head First Design Pattern) book well known at Javaranch.
Protection recommended was method synchronization, or even better some critical block code synchronization.

But I find this question particulary silly and vicious, as question should state the multithread context, for code is perfectly correct in standard environment. I dont like to imagine potential problems due to potential different unspecified environments, this multithread feature should be clearly stated.
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

But I find this question particulary silly and vicious, as question should state the multithread context, for code is perfectly correct in standard environment. I dont like to imagine potential problems due to potential different unspecified environments, this multithread feature should be clearly stated.
Multi-threading issues are very much common place in a standard environment. It is as simple as 2 concurrent calls to the Instance() method which is so so likely to happen. You do not need some fancy environment to make this happen. Hence, synchronizing is extremely important.
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You are testing the member "_instance" for null twice each time - once is enough.

Nope, it is necessary to check it twice. However, the double null check happens only for the first execution. For every subsequent execution, it is always "not null" and will not go into the synchrnized block, and hence there will only be a single null check. The only way to avoid the double check on first execution is to move the null check into the synchronized block (equivalent to synchronizing the whole method), however, this would result in synchronization overhead each time the Instance() method is invoked. Hence the double null check is the best solution.


Also, you can still get away with doing "Singleton s = new Singleton()" and create your own instance from a class in the same package (bypassing the Instance() method) since the constructor is not private, which defeats the whole purpose of a Singleton class.
Again no. The constructor is protected. Hence any class in the package cannot do "Singleton s = new Singleton()". Only a subclass can do that; and it might be legal to do so considering that it is a subclass of the singleton; however, that could be debatable; also could be done depending on the need.
[ September 18, 2005: Message edited by: soniya saxena ]
 
Peter Chun
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by soniya saxena:
it is necessary to check it twice.
which defeats the whole purpose of a Singleton class



Not true.

Double-checking simply won't work.

Singleton problem in multi-threaded environment has been discussed a lot in other places.

This is a well-know issue, and kind of hard to grasp without understanding of Assembly language (especially, out-of-order write).



http://www.ibm.com/developerworks/java/library/j-dcl.html


In short, the best answer is:


[ September 18, 2005: Message edited by: Peter Chun ]
 
Sonny Gill
Ranch Hand
Posts: 1211
IntelliJ IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Grr...you beat me to it Peter

I was just about to say what's wrong with creating the Singleton instance when you declare it.
I suspect there are only very few cases where you need lazy instantiation, perhaps when/if the getInstance() method needs to be passed arguments at Runtime...but then it would perhaps be a Factory method or something.
 
Victor Banerjee
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Michael Ernest:
If it's an interview question, then let's put it in Jobs Discussion.


Hi Sheriff, Pardon me but since this is a real techie question, it may belong to one of the Java forums. Aren't we diluting the other precious job related discussions by permitting such technical posts here.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are interview parts to this question that have been touched on but not explored yet.

Peter Chun: (etc etc) Double-checking simply won't work. (etc etc) In short, the best answer is: (etc etc)

This is what I was hoping for in terms of a solution, the other samples should be used with care. This code does not lazy load the instance, but this is unlikely to be an issue in a Singleton

Back to the interview part:
From the fact that the original poster's friend didn't know the answer and the various samples given that this thread it is clear that this is not a simple question. The number of matching conversations that can be found around the ranch also support this. I wish I had a dollar for every broken or dangerous Singleton implemenation Ive seen, some I wrote myself

I like Eric's comment that it only makes a difference in multi-threaded environment. Therefore a valid answer (with qualification) is that there is nothing wrong with the code sample.

In an interview it would be sufficient to say that it is not thread-safe, but they'd probably ask for a description of a solution and Peter's code would work.

Depending on the depth you want to go into, you could also discuss lazy loading, double check locking and the problems in Java, possible solutions in JDK 1.5 using the volatile keyword, you could even discuss the problem with mutable singletons which contain state.

Personally I don't think they intend to fill the entire interview with this question, but in a technical interview situation the interviewer is usually looking for an understanding of the deeper issues with the problem, so anything may help.
 
omkar patkar
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys......the topic is getting heated!..............actually.....i forgot to mention.........in the q that, the snippet is java/c# code!....but i don't think that would make much diff!

i asked one of my frnd working in c# he said ....that its usually wrng practice to refer to an object of same type as a class member......b'coz "POTENTIALLY" in future if we create n objects of Singleton......then referneces present in class members of previous Singeleton objects are lost.....due to garabage collection and we will never be able to use n-1 objects.....i don't get this explanantion either!...........also what has threading got to do with Potenial problem ?

i really thinkthis kind of interview q is really not an interview q !.....i am totally pissed off thinkin over the q!
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
omkar, Please reduce your usage of abbreviations. See the link here.

I also have another request:
Can yiou tell us where the question really comes from? I'm not convinced it is an interview question.
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi david, any specific reason why you are not convinced. to me, it seems a very normal interview question.

Originally posted by David O'Meara:
omkar, Please reduce your usage of abbreviations. See the link here.

I also have another request:
Can yiou tell us where the question really comes from? I'm not convinced it is an interview question.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it looks like it could be an interview question.
No, I'm not convinced that this is where it comes from. My data suggests it comes from 'somewhere else'.
 
Mani Venkatesan
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David O'Meara:
Yes, it looks like it could be an interview question.
No, I'm not convinced that this is where it comes from. My data suggests it comes from 'somewhere else'.



For the record, I have been asked this question myself.

In my case, I was also asked to think about enforcing the singleton pattern in a multi-classloader environment.
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by soniya saxena:
Again no. The constructor is protected. Hence any class in the package cannot do "Singleton s = new Singleton()". Only a subclass can do that; and it might be legal to do so considering that it is a subclass of the singleton; however, that could be debatable; also could be done depending on the need.


So if I create the singleton class as above and place it into a package called X, and then write another class within the same package with "Singleton s = new Singleton()", do you think that this will not compile and run?
[ September 20, 2005: Message edited by: K Riaz ]
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the problem is with protected constructor. It does not make sense to subclass Singleton since Instance() will always create base Singleton and it cannot be overriden, because it's static.

I think with all this multi-threaded discussion you off too far
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my case, I was also asked to think about enforcing the singleton pattern in a multi-classloader environment.


That is really funny interview question. Almost rivals with "what I have in my pocket?"
 
Robert Watkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by soniya saxena:
Multi-threading issues are very much common place in a standard environment. It is as simple as 2 concurrent calls to the Instance() method which is so so likely to happen. You do not need some fancy environment to make this happen. Hence, synchronizing is extremely important.


The "standard environment" is what you get when you invoke a main() method - you will only have one thread until you spawn more.

Now, if your normal environment has threads, that's fine - my normal environment has multiple class loaders, and the example code isn't sufficient in that example at all.

Furthermore, the double-checked locking only works reliably in Java 5, and then only if the variable is declared to be volatile; in earlier versions of Java, and with non-volatile variables, you are better off making the method synchronized and not bothering with the initial null check.

Finally, for a "true" Singleton, you should have a private constructor to avoid an external class initialising you.
 
Robert Watkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by soniya saxena:

Also, you can still get away with doing "Singleton s = new Singleton()" and create your own instance from a class in the same package (bypassing the Instance() method) since the constructor is not private, which defeats the whole purpose of a Singleton class.
Again no. The constructor is protected. Hence any class in the package cannot do "Singleton s = new Singleton()". Only a subclass can do that; and it might be legal to do so considering that it is a subclass of the singleton; however, that could be debatable; also could be done depending on the need.


*cough* You just failed one of my standard interview questions with that statement... any class in the same package has full access to the protected methods, variables, and constructors.
[ September 21, 2005: Message edited by: Robert Watkins ]
 
Robert Watkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vladas Razas:


That is really funny interview question. Almost rivals with "what I have in my pocket?"


What's funny about it? Multi-classloader environments need Singletons too, you know... (well, at least as much as single-classloader environments need Singletons)
 
Robert Watkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sonny Gill:
I suspect there are only very few cases where you need lazy instantiation, perhaps when/if the getInstance() method needs to be passed arguments at Runtime...but then it would perhaps be a Factory method or something.


Actually, another good reason is if the construction can thrown an exception - having exceptions come out of a getInstance method is a lot nicer than having one exception, followed by a zillion ClassDefNotFoundErrors.
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's funny about it? Multi-classloader environments need Singletons too, you know... (well, at least as much as single-classloader environments need Singletons)


Not sure what is meant by "multi-classloaders eviroment". Either the question is too specific or not-well formed, IMO. This way interviewer will filter out 99 of 100 or 199 of 200 Java programmers.
Did you mean "how singleton would work in distributed web application?" ?
 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Singelton pattern looks like a "favorite" interview question in India.
When asked to write code for a singleton pattern most of them go for lazy initialization with synchronized method.

I never have felt the need to use lazy initalization approach.

what about java.awt.Toolkit and java.lang.Runtime ?
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When asked to write code for a singleton pattern most of them go for lazy initialization with synchronized method.

I never have felt the need to use lazy initalization approach.


I never have felt the need to make getInstance() synchronized
 
Robert Watkins
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vladas Razas:

Not sure what is meant by "multi-classloaders eviroment". Either the question is too specific or not-well formed, IMO. This way interviewer will filter out 99 of 100 or 199 of 200 Java programmers.
Did you mean "how singleton would work in distributed web application?" ?


No, I meant how would you do Singleton in an environment where you have multiple class loaders within a single JVM, _without_ JNDI.

Static variables are associated with the class - if a class is loaded in more than one class loader, you may well get multiple instances of static variables.

By contrast, the Singleton in the distributed application is fairly easy - that's what JNDI is for.
 
soniya saxena
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
gosh ... and to think that I got away with that all these years
anyways, I am sorry for posting incorrect information guys...

Originally posted by Robert Watkins:


*cough* You just failed one of my standard interview questions with that statement... any class in the same package has full access to the protected methods, variables, and constructors.

[ September 21, 2005: Message edited by: Robert Watkins ]
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

No, I meant how would you do Singleton in an environment where you have multiple class loaders within a single JVM, _without_ JNDI.

Static variables are associated with the class - if a class is loaded in more than one class loader, you may well get multiple instances of static variables.


So what would be the correct answer? ( I would fail your interview )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic