Morgan Stanley Interview Question for Java Developers


Country: India
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
1
of 3 vote

Here is the implementation in java:

// Correct multithreaded version
class Foo { 
  private Helper helper = null;
  public synchronized Helper getHelper() {
    if (helper == null) 
        helper = new Helper();
    return helper;
    }
  // other functions and members...
  }

- Rage January 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 votes

This was the first answer I gave. But this implementation sucks , as it blocks all requesting threads that need only to fetch object reference. To make it efficient , solution has to be that we can get Singleton object reference anytime , since its a read only meahod.

private static SingletonObject obj;
SingletonObject getReference()
{
if (obj!=null)
return obj;
else
{
synchronized(this)
{
while(obj==null)
{
obj = new SingletonObject();
}
return obj;
}
}}

- Saurabh January 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Isn't so simple like this

private static SingletonObject obj = new SingletonObject ();
SingletonObject getReference()
{
return obj;
}
}}

- mathukolappan June 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

class Singleton
{
          private:
                Singleton();
                Singleton(const Singleton &copy);
                const Singleton& operator=(const Singleton &rhs);
          public:
                static Singleton& GetInstance()
                {
                      static Singleton _instance;
                      return _instance;
                 }
};

- kumarbijendra January 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Singleton is a DP where only a single object of the class can be created.

class Singleton{
private :
Singleton();// Constructor is private
public :
Singleton & getInstance()
{

// Add thread lock here to make it thread safe
if(!object)
object=new Singleton();
// Release Lock
return object;

}
}

static *Singleton object=NULL; // Static Object must in C++ not required in Java

- hprem991 January 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this isn't gonna be thread safe. I think is specifically meant for a Java developer position.

- Rage January 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

There are various well tested design practices called design pattern that tells how to structure your classes and interfaces to solve a problem which enhances maintainability and extendanbility. ie: Strategy Design patten , Decorator design pattern , Factory design pattern , Iterator and yes my favorate ie most simplest and most frequently asked in tech interview -Singleton Design pattern :It gives you a well tested and accepted method that solves how to instantiate one and only one object for a given class ans gives a global point of access to it without having the downside of global variable in language like C++. Looks simple and mouthful right??:P.


This design patterns is something like:

Algo:


Create a class called Singleton
declare its state and behaviour with one private static volatile Singleton type variable called uniqueInstatnce.
Make constructor as private so that only class can create object.
add private static method(interface to create object) as below:

public static getInstance(){
if(uniqueInstance==NULL){
synchronized(this){
if(uniqueInstance==NULL){
uniqueInstance=new Singleton();
}
}
return uniqueInstance;
}

- Deepak Singh January 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Singleton{
private static Singleton instance=null;
private Singleton() { }
synchronize private static void createInstance(){
if(instance==null)
instance=new Singleton();
}
public static Singleton getInstance() {
if(instance==null)
{
createInstance();
}
return instance;
}
}

- vipin khatri February 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

just call this getInstance method with class name and get singleton object and it also thread safe..........

- vipin khatri February 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

my 2 cent

package designpattern;

import java.util.concurrent.CountDownLatch;

import com.vikalp.util.LOG;

import designpattern.SingltonExample.MyEnumSingleton;

public class SingltonExample {
	
	
	//throw exception on clone method 
	private static volatile SingltonExample instance;
	
	
	private SingltonExample(){
		System.out.println("sfdf dfdf");
	}

	//In an effort to make this method more efficient, an idiom called double-checked locking was 
	//created.The idea is to avoid the costly synchronization for all invocations of the method
	//except the first. The cost of synchronization differs from JVM to JVM. In the early days,
	//the cost could be quite high.As more advanced JVMs have emerged, the cost of synchronization
	//has decreased, but there is still a performance penalty for entering and leaving a 
	//synchronized method or block. Regardless of the advancements in JVM technology, programmers
	//never want to waste processing time unnecessarily.

	//This can still fail with multi processor
	public static  SingltonExample getInstance(){				
		
		// synchronized only when instance is null so we can save synchronization cost		
		if(instance == null){			
			synchronized(SingltonExample.class){	// one one thread can enter here			
				if(instance == null){
					instance = new SingltonExample();
				}
			}
			
			return instance;
		}
		else{
			return instance;
		}		
	}	
	
	
	 void rest(String name) throws InterruptedException{
		 LOG.debug("Resting the instance---Thred name "+name);
		Thread.sleep(1000);
	}
	
	public Object clone() throws CloneNotSupportedException {
		 //throw new CloneNotSupportedException();
		return super.clone();
	}
	
	public static void main(String[] args){
		SingltonExample myCopy = SingltonExample.getInstance();
		LOG.debug(myCopy);
		
		CountDownLatch startLatch = new CountDownLatch(1);
		
		for (int i=0;i<50;i++){
				new Thread(new client(startLatch," Thread:"+i)).start();
		}
		
		startLatch.countDown();
				
	}
	
	//java 1.6 onwards
//	package mypackage;
//
	public enum MyEnumSingleton {
		INSTANCE;
		
		private MyEnumSingleton(){
			LOG.debug("-----");
		}
		
		 void rest(String name) throws InterruptedException{
			 LOG.debug("Resting the instance---Thred name "+name);
			Thread.sleep(1000);
		}
		// other useful methods here
	}
	
	/*
	 * Another good way
	 */
//	  public class Sing{
//	  private static instance = new Sing();
//	  private Singh()
//	  {
//	  }
//	  public static Sing getInstance(){
//	   return instance;
//	  }
	
}

class client implements Runnable{

	CountDownLatch latch;
	String name;
	client(CountDownLatch latch,String name){
		this.latch = latch;
		this.name = name;
	}
	
	@Override
	public void run() {
	
		try {
			latch.await();
//			SingltonExample myCopy = SingltonExample.getInstance();
//			LOG.debug(myCopy);
//			myCopy.rest(name);
			
			MyEnumSingleton.INSTANCE.rest(name);
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// TODO Auto-generated method stub
		
	}
	
}

- http://javadecodedquestions.blogspot.sg/2012/03/java-interview-with-investment-bank-4.html February 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Singleton {
private static Singleton singleton = null;

private Singleton() {}

public static Singleton getInstance() {
if(singleton==null) {
synchronized (Singleton.class) {
if(singleton==null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}

- xuqin1019 February 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Singleton{

private volatile static Singleton uniqueInstance;

private Singleton(){}

public static Singleton getInstance(){

if(uniqueInstance == null){

synchronized(Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}

}

}
return uniqueInstance;
}

}

- huang3981658 March 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

easiest way to create a singleton is by using enums..They are thread safe, The instance will be static and final by default.
enum Singleton{
INSTANCE;
}

- Aditya June 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Singleton1 {

private Singleton1(){}

protected static Singleton1 s1 = null;

public static Singleton1 getInstance(){
if(s1==null){
synchronized(Singleton1.class){
s1 = new Singleton1();
}
}
return s1;
}
public void method(){
System.out.println("obj created");
}

}

- Anonymous August 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Singleton1 {

	private Singleton1(){}
	
	protected static Singleton1 s1 = null;
	
	public static Singleton1 getInstance(){
		if(s1==null){
			synchronized(Singleton1.class){ 
			s1 = new Singleton1();
			}
		}
		return s1;
	}
	public void method(){
		System.out.println("obj created");
	}
	
}

- Akshansh August 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can use below approach in C#. Its called Double - locking technique.

public class MySingleton
    {
        private static MySingleton s_UniqueInstance;
        //Any light weight object for locking.
        private static readonly Object s_ObjectToLock = new Object();

        private MySingleton()
        {
        }

        public static MySingleton UniqueInstance
        {
            get
            {
                if (s_UniqueInstance != null)
                {
                    return s_UniqueInstance;
                }

                lock (s_ObjectToLock)
                {
                    MySingleton tmp = new MySingleton();
                    if (s_UniqueInstance != null)
                    {
                        Volatile.Write(ref s_UniqueInstance, tmp);
                    }
                }
                return s_UniqueInstance;
            }
        }
    }

- Vinay February 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;
 
    // private constructor
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }

}

- rahulkgupta December 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;
 
    // private constructor
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }

}

- rahulkgupta December 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;
 
    // private constructor
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }

}

- rahulkgupta December 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;
 
    // private constructor
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }

}

- rahulkgupta December 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C++ 11 static initialization is guaranteed thread-safe, so:

class Singleton
{
	public:
		static Singleton& instance()
		{
			static Singleton instance; // in C++ 11 standard guaranteed thread-safe without dead-locks
			return instance;
		}
		
	private:
		Singleton()
		{
		}
		
		Singleton(const Singleton&) = delete;
		Singleton(Singleton&&) = delete;		
};

- Leo July 31, 2015 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More