Goldman Sachs Interview Question
Java DevelopersCountry: United States
Interview Type: Phone Interview
How can double checked lock help here? It is only used to make sure there is no race condition while initializing a singleton object. Constructor can still throw an exception.
Use double checker to create the instance while creation u handle the exception or u can throw the exception to the caller.
Lazy loading is the correct methodology to handle this type scenarios.
Sample Program with single tons
<b>Please correct if i am wrong</b>
import java.io.IOException;
public class TestSingleTon {
public TestSingleTon() {
super();
}
public static void main(String[] args) {
SingleTon1 one = SingleTon1.getInstance();
SingleTon2 two = SingleTon2.getInstance();
System.out.println(one == one.getInstance());
System.out.println(two == two.getInstance());
}
static class SingleTon1 {
private static SingleTon1 br;
private SingleTon1()throws IOException {
}
static {
try {
br = new SingleTon1();
System.out.println("Done With Instacnce1");
} catch (IOException e) {
e.printStackTrace();
}
}
public static SingleTon1 getInstance() {
return br;
}
}
static class SingleTon2 {
private static SingleTon2 br;
private SingleTon2()throws IOException {
}
public static SingleTon2 getInstance() {
if(br==null) {
synchronized(SingleTon2.class) {
if(br==null) {
try {
br = new SingleTon2();
System.out.println("Done With Instacnce2");
} catch (IOException e) {
e.printStackTrace();
//Either u can handle it here or u can thorw it back to the caller
}
}
}
}
return br;
}
}
}
You can achieve this Lazy loading with Exception handing in Constructor - For complete program u can refer to this link - javadiscover.com/2013/02/how-to-create-fully-singleton-design.html
I think whoever is trying to get the SingleTon instance of that class should handle the exception. SingleTon class have to just throw it to the caller. It should be always caller's responsibility what action he have to take if some exception occurs.
class TestSingleTon{
private TestSingleTon() throws IOException {
}
public static synchronized TestSingleTon getInstance() throws IOException{
return new TestSingleTon();
}
}
Sorry above code is not for SingleTon. It will always return a new instance.Exact code will be
class TestSingleTon{
private static TestSingleTon INSTANCE=null;
private TestSingleTon() throws IOException {
}
public static synchronized TestSingleTon getInstance() throws IOException{
if(INSTANCE==null){
return new TestSingleTon();
}
return INSTANCE;
}
}
Double Checker Approach
- Prakash September 11, 2013