Goldman Sachs Interview Question
Software Engineer / DevelopersYou might even want to synchronize the get instance method, so that it doesnt create 2 instaces when 2 threads are accessing simultaneously. This case is 100% possible though in a rare scenari0.
private static final Singleton INSTANCE = new Singleton(); JVM will ensure that only one static instance so there will be not a case that 2 instaces when 2 threads are accessing
package com.sanjeeb.singleton;
/**
* Properties of a singletonFactory
* Private constructor
* Static getInstance Method
* static variable to return the instance
* clone method overriden
*
*/
public class SingletonFactory {
private static final TestClass testClass = new TestClass();
private SingletonFactory(){}
public static synchronized TestClass getInstance() {
return testClass;
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning not supported");
}
}
class TestClass {
private final int numberOfDaysInFebInALeapYear=28;
public int getNumberOfDaysInFebInALeapYear() {
return numberOfDaysInFebInALeapYear;
}
}
If a class does not implement Cloneable interface, doesn't java automatically throw CloneNotSupportedException?
1. Define a private static attribute in the “single instance” class.
- biggied88 March 04, 20102. Define a public static accessor function in the class.
3. Do “lazy initialization” (creation on first use) in the accessor function.
4. Define all constructors to be protected or private.
5. Clients may only use the accessor function to manipulate the Singleton.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}