Bloomberg LP Interview Question
Software Engineer InternsCountry: United States
Interview Type: Phone Interview
instance variable should be static
package career.cup.bloomberg;
public class Singleton {
public static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance(){
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
As name suggest Singleton create only one object. it is more useful in such situation like when you have only 1 DB license & you want to allow only one connection object of the DB.
Refer below link becoz it has different types of singleton examples
journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples
Add "synchronized" keyword to make the code thread-safe.
public class Singleton{
private Singleton instance;
private Singleton(){}
public static synchronized getInstance(){ // Add synchronized keyword to make it thread-safe
if(instance == null)
return new Singleton();
else
return instance;
}
}
public class SingletonExample {
private static SingletonExample single;
private SingletonExample() {
}
static {
if (single == null) {
try {
single = new SingletonExample();
} catch(Exception e){
e.printStackTrace();
}
}
}
public static SingletonExample getInstance() {
return single;
}
}
class test {
public static void main(String args[]) {
SingletonExample abc = SingletonExample.getInstance();
}
}
One of the Better way of writing a Singleton is using the Static Inner Helper Class (Bill Pugh Method).
public class Singleton {
private Singleton(){}
private static class SingletonHelper{
private static final Singleton m_instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonHelper.m_instance;
}
}
When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.
This is the most widely used approach for Singleton class as it doesn’t require synchronization.
public class Test {
private Test _instance = null;
private Test(){
}
public Test getInstance(){
if(_instance == null)
return new Test();
return _instance;
}
}
Singleton classes lets you have only once instance of the class. For example, in android application development the same activity class has to be used for user interaction thus a singleton class is used.
public class Test {
private Test _instance = null;
private Test(){
}
public Test getInstance(){
if(_instance == null)
return new Test();
return _instance;
}
}
Singleton classes lets you have only once instance of the class. For example, in android application development the same activity class has to be used for user interaction thus a singleton class is used.
please review my code and let me know if any enhancement is required
package com.rk.core.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class PureSingleton implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -1526499224432020993L;
private static PureSingleton instance = null;
private static Object mutex = new Object();
private PureSingleton() {
}
public static PureSingleton getInstance() {
if (instance == null) {
synchronized (mutex) {
if (instance == null)
instance = new PureSingleton();
}
}
return instance;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("PureSingleton cannot be cloned");
}
private Object readResolve() throws ObjectStreamException {
return getInstance();
}
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
PureSingleton instanceOne = PureSingleton.getInstance();
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
"filename.ser"));
out.writeObject(instanceOne);
out.close();
// deserailize from file to object
ObjectInput in = new ObjectInputStream(new FileInputStream(
"filename.ser"));
PureSingleton instanceTwo = (PureSingleton) in.readObject();
in.close();
System.out.println("instanceOne hashCode=" + instanceOne.hashCode());
System.out.println("instanceTwo hashCode=" + instanceTwo.hashCode());
try {
PureSingleton instanceThree = (PureSingleton) instanceOne.clone();
System.out.println("instanceThree hashCode="
+ instanceThree.hashCode());
} catch (CloneNotSupportedException e) {
System.out.println(e.getMessage());
}
}
}
Double checked locking is broken in java 1.4 and before. So you have to use volatile keyword for the instance variable and that too only in java 1.5+
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.
- Anonymous December 19, 2014