Amazon Interview Question


Country: India




Comment hidden because of low score. Click to expand.
4
of 4 vote

Problem: You have to synchronize the getInstance() method, because there is a possibility that while one thread is creating the singleton instance for the first time (this is point just before the new() is called to created the instance), the other one might be also executing the getInstance() method and checking if the instance is already created. Since the instance is not created yet by thread one, the second thread will see that the instance is null and try to create it again.

Solution: You can either synchronize the getInstance() method, which will be expensive. So, there is a better approach called "double checked locking", where you only synchronize the part where the instance is created. This is less expensive than synchronizing the whole method, but you check the instance again for nullness in the syncronized block before creating it.

- oOZz July 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good answer.

- King@Work July 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Synchronizing only the part where the instance is created is not by itself considered double-checked locking. There has to be a double check. Specifically, the pattern is something like

if (instance == null) {
    lock (this) {
        //if still null after lock has been acquired
        if (instance == null) {
            instance = new MySingleton ();
        }
    }
}

Though seemingly clever, this pattern actually has well-known problems in many cases and is often considered an anti-pattern. See the Wikipedia article on "double-checked locking".

- Anonymous July 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

DCL alone cannot solve the problem completely. In Java, you ought to combine the usage of 'volatile' keyword with Double Checked Locking, why because 'volatile' ensures memory visibility across all the threads when updates to a variable are made.

In the above post, 'instance' has to be declared volatile, so when another thread has set its value, the 'if (instance == null)' check in the code below works correctly in the current thread.

//if still null after lock has been acquired
        if (instance == null) {
            instance = new MySingleton ();
        }

Not sure how to get the DCL anti-pattern work correctly in other languages.

- Murali Mohan July 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Dumbo Good point. Though the known problems with DCL are not due to the double checked locking pattern, but due to the programming language used to implement the pattern. For example, for non static singleton instance version, like you've suggested, Java fixed this issue by using volatile for the singleton instance (Also note that this is Java 5 and up). You don't have to use volatile instance, for instance for the static version, a final static wrapper object, can also be used in Java.

- oOZz July 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

your answer is correct, but double checking lock won't solve problem completely. There was a problem due to java memory model, that is it allows out of order writes. Using volatile everything will be solved, since its atomic varible.

- Sairam Yendluri July 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good answer, keep only small part of code inside "syncronized" block. That is less expensive.

- Sharma July 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

I forgot to mention with the question, its for C++ and not java. It was asked to code single singleton in C++ and then suggest possible measures to make it thread safe. The stress was on proper use of MUTEX and semaphors.

- Nascent July 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Don't ever try "double checked locking". It has been debated and proven in the past 10 years to be bad approach.

- Anonymous July 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Could you please give references to something that proves "double checked locking" bad?

- Prithvi July 03, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

This can be done by Double locking with synchronized block:

public static Singleton getInstance()
	{
		if (instance == null)
		{
			synchronized(Singleton.class)
			{
				if (instance == null)
				{
					System.out.println("getInstance(): First time getInstance was invoked!");
					instance = new Singleton();
				}
			}            
		}

		return instance;
	}

- Md Husain July 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static class SingletonHolder
{
static Singleton instance = new Singleton();
}


public static Singleton getInstance()
{
return SingletonHolder.instance ;
}

- zz7zz7zxz July 03, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Singleton
{
private:
  Singleton(){};
 ~Singleton();
public:
  static Singleton * getInstance(){
       static Singleton inst;
       return &inst;
}
};

In c++11, this is thread safe.
For previous versions of c++11, we have to use volatile and DCLP.

- king July 03, 2013 | 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