0

In the given link ,take a look at the options given and select the option that describes the worst thing with this code:

https://gist.github.com/d34th4ck3r/49e9ae56458d4ed0f8ae

d34th4ck3r
  • 719
  • 2
  • 11
  • 38

3 Answers3

4

More than one instance of Mango can be created

Yes: if two threads execute getInstance concurrently, they could both see INSTANCE null and create a new instance

A Mango will never be created

huh... if you call getInstance, an instance will be created, so no.

The constructor is private and can't be called

No, it can be called from within the class by getInstance

value can be garbage collected, and the call to getInstance may return garbage data

INSTANCE will not be garbage collected as long as it is reachable - in the case of a static variable, that is for the whole life of the JVM (*).

(*) more precisely, it will not be garbage collected as long as the class is loaded. A class could be unloaded if the associated classloader itself is garbage collected.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

this is the classic singleton object design pattern

whats worst about is dependent on the requirement. as per my understanding if this is a class of the larger program, then mango should never be made more than once.

as assylias said, until there is a synchronized keyword the result may lead to 2 objects of mango(but thats a corner case)

synchronized public static Mango getInstance()
    {
        if ( INSTANCE == null )
        {
            INSTANCE = new Mango();
        }
        return INSTANCE;
    }
Fr_nkenstien
  • 1,923
  • 7
  • 33
  • 66
0

I think the answer is option A : "More than one instance of Mango can be created" Without proper sychronization,two or more threads may call getInstance() concurrently and that make Mango an unqualified Singleton

By the way, this looks like a homework or interview question!:)

Harry.Chen
  • 1,582
  • 11
  • 12