Which is the Best Java Web Framework ?

Java - Interview Questions - Design Pattern - Singleton

Q1. What is Singleton ?

Ans. It's a Design Pattern.

Q2. What is a Singleton Class ?

Ans. Class using which only one object can be created.

Q3. What is the use of such a class ?

Ans. There could be situations where we need not create multiple objects and hence Singleton can help in saving resources by avoiding creating new objects every time a request is made. Moreover these classes can also be helpful if we want a object to be shared among threads.

Q4. Are u using Singleton in your code ?

Ans. Yes, for Database connection and Property files.

Q5. Write the code for a Singleton Class ?

Ans.


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

Q6. Why have we used synchronized here ?

Ans. getInstance method can be accessed from two points simultaneously and in such case 2 instances may get created. Synchronization will make sure that the method gets accessed one by one for each call and the same object is returned for the second call.

Q7. Why have we declared the instance reference volatile ?

Ans. That's an instruction to JVM that the variable is getting accessed by multiple locations and hence don't cache it.

Q8. Can we make the reference instance non static ?

Ans. No , as non static variables cannot be accessed through static methods.

Q9. Can we have this pattern implemented using Static Class ?

Ans. Though we can implement this behavior using static class , but we should never do it.

Q10. What are the problems in implementing this patterns using static Class ?

Ans. 

a. We cannot achieve runtime Polymorphism or late binding as Java doesn't allow overriding static methods.
b. We cannot do lazy initialization as Static members are loaded during class loading only.
c. We cannot serialize as Java doesn't serialize static members.


Submit a Question today. We will publish it with credits to you.
Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.