Hi
This question ask me in a interview i have dont idea about it.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted May 2, 2012, 8:53 AM EDT
Check out this thread:
http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java
Satyapriya NayakRank #47 · 31.5K reputationPosted May 2, 2012, 9:01 AM EDT
Singleton pattern used when we want to allow only a single instance of a class can be created inside our application. Using this pattern ensures that a class only have a single instance by protecting the class creation process, by setting the class constructor into private access modifier.
To get the class instance, the singleton class can provide a method for example a getInstance() method, this will be the only method that can be accessed to get the instance.
package org.kodejava.example.pattern.factory; public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static synchronized Singleton getInstance() { return instance; } public void doSomething() { for (int i = 0; i < 10; i++) { System.out.println("i = " + i); } } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not allowed."); } }There are some rules that need to be followed when we want to implement a singleton.
clone()method of thejava.lang.Objectclass and throwCloneNotSupportedExceptionso that another instance cannot be created by cloning the singleton object.And this is how we use the
Servicesingleton class.package org.kodejava.example.pattern.factory; public class SingletonDemo { public static void main(String[] args) throws Exception { // // Gets an instance of Service object and calls the // doSomething method. // Singleton service = Singleton.getInstance(); service.doSomething(); } }Please refer the below links
http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html
http://www.kodejava.org/examples/12.html
Thanks
MuthuMari MRank #5,738 · 288 reputationPosted May 2, 2012, 9:13 AM EDT
singleton pattern must satisfy the single instance and global access .
Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.
pls refer this url
http://www.javabeginner.com/learn-java/java-singleton-design-pattern
thanks.
If this post is useful then mark it as "Accepted Answer"