Qualcomm Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
If you really need that kind of dark bizarre voodoo behavior, you can use synchronization when creating the objects and a finalizer to decrement the object count when an object gets GC'd. But since GC is not guaranteed to run at any particular time, doing this kind of stuff is usually a worse idea than it seems.
import java.util.ArrayList;
import java.util.List;
public class FivetonImpl {
public static void main(String[] args) {
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
System.out.println(Fiveton.getInstance());
System.gc();
System.out.println(Fiveton.getInstance());
}
}
class Fiveton
{
int value;
static List<Fiveton> freeFives = new ArrayList<Fiveton>(5);
static {
freeFives.add(new Fiveton());
freeFives.add(new Fiveton());
freeFives.add(new Fiveton());
freeFives.add(new Fiveton());
freeFives.add(new Fiveton());
}
public static synchronized Fiveton getInstance()
{
if(freeFives.size() > 0)
{
return freeFives.remove(freeFives.size() - 1);
}
return null;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize called");
freeFives.add(new Fiveton());
}
}
In a singleton pattern, the class always has a reference (static) to the object. Extend this to 5 object references and you have a Fiveton. I presume that the class using the singleton object must know which object to use.
- axecapone July 24, 2012A clarification: So when an object is GCed, you decrement count, create new object but not increment count again??
In this pattern, the object does not get GCed unless you explicitly release the reference and create a new object simultaneously. Additionally if the object is getting GCed and constructed, then make the references 'volatile' to prevent any concurrency issues.