I dont understand the concept of a singleton class - java

I know how to make a singleton class in java but what I dont understand is the concept of singleton. Like why would I need a singleton class and why would I use a singleton instead of a regular class?
"Singleton pattern restricts the instantiation of a class and ensures
that only one instance of the class exists in the java virtual
machine."
I just read that definition but I dont get it, what does it change if there is one or more instances of a class.
Why would I want to only have one instance of a class.

In some cases, we need to expose a shared resource throughout the application e.g. DB connection but we don't want to
create shared object up-front (before creation of client objects).
explicitly pass shared object to each client object.
then we can use Singleton design pattern.
Typical Singleton class looks like
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
But we can achieve the similar behaviour by making each and every instance methods which are exposing business operation as static. In this approach we don't even need to create single object.
Then why do we need Singleton?
Well, the answer is simple. To isolate actual implementation from the client. Basically we are applying abstraction OOP principle here.
This is helpful If the singleton class is part of library which is used by various clients and library wants to vary the implementation as per the client.
Sample for such singleton can be
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingletonChild(); // here we are creating an object of subclass of MySingleton.
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
Hope this help in understanding Singleton design pattern.

Singletons are used for when you want exactly one instance of a class, that the entire application shares.
Good examples for this principle are classes that are in charge of accessing external resources. For example, you'd want the entire application share the same database connection (or at least connection pool), not have every class that needs it open its own connection.

Singletons are classes with properties which can be shared with other classes in the same context. (Application, session, ...)
For example if you have to count the number of connected users in a web application. Every time a user connect, you increment a counter in a unique shared class.

Related

When should I use lazy Singletons over normal Singletons?

So far I have seen two examples of Singletons.
Normal Singletons,
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
// hidden constructor
}
public static Singleton getInstance() {
return instance;
}
}
and Lazy Singletons,
public class Singleton {
private Singleton() {
// hidden constructor
}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Coding is from this thread and this user. I have just recently gotten into trying to learn Singletons as my previous methods have been
1.) Using static in order to create something like ...
static MyClass instance;
2.) I would attempt to pass an instance in a seemingly odd way,
MyClass instance;
#Override
public void onEnable() { instance = this; }
// Transition to different class - - -
public OtherClass(MyClass myClass) {
this.instance = myClass;
}
Lastly, what is my end goal? I am mainly using it in order to pass variables from my main class to other classes. I'm currently attempting to learn how to properly use Files and FileConfiguration, so I want to easily share them throughout my classes.
If I seem like a beginner, instead of going out of your way to tell me to learn Java, please provide a resource to help me with my problem first and foremost.
As to when, rather than how: I would use lazy instantiation of a singleton or of any other object when there is a fair chance of the object not being needed, and immediate instantiation when the likelihood of it being needed is high. In general, if instantiation were to fail, and the object is needed, it is better that it fail as early as possible.
This link explains it fairly well and even uses a similar example.
In software engineering, the initialization-on-demand holder (design pattern) idiom is a lazy-loaded singleton. In all versions of Java, the idiom enables a safe, highly concurrent lazy initialization with good performance.
Regarding why you should use this: if the creation of this instance is expensive, then this design pattern essentially delegates the expensive computation for when it is needed, rather than when the outer class, Singleton in your case, is first accessed.
Another reason is given by this other link. It states:
A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class.

Same instance sharing with multiple requests in Java (OOP)

I have one class whose single instance needs to be used by multiple classes in Java. I found two solutions for the same:
1. Pass the instance as method parameters
2. Use Static factory
My question is if I used static factory, how can I differentiate the incoming requests when I am using the static method. I want to avoid the 1st solution as there are many classes that are going to use this instance. Also, recommend the best design if other than mentioned above.
Code Example:
class MyClass{
Map<String, List<String>> myMap=new ConcurrentHashMap();
public static void addToMap(String key, String value){
if(myMap.containsKey(key)){
List<String> stringList=myMap.get(key);
stringList.add(value);
}
else{
myMap.put(key,value);
}
}
}
I want to perform this add method at many places while program execution for eg:
Method addEmployee():
if(employeeName==null){
MyClass.addToMap("ER101", "Name Error");
}
Method insertInDB():
catch(SQLException e){
MyClass.addToMap("SQL", "Error Occurred in DB Operation");
}
Thanks
There are a number of ways to make the same instance of a class available to different callers such as threads or requests.
One of the easiest things you can do is create a singleton as shown above. The problem with singletons is that there can only ever be one of them, as they are generally set up to enforce that there is a single instance of them.
Better is to create your instance, and pass it to the things that need it. If you're creating a web application or similar, you can use a Dependency Injection framework such as SpringFramework to achieve this.
Injecting your instance where it is needed will mean it will be easier to replace this instance with a dummy instance for testing, and during testing you'll be able to create many instances of this class configured in different ways to test.
As 12dollar says: Use the Singleton Design Pattern, and ask for that instance to the Singleton Class:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then you could call getInstance().
The best design would be to make your class as Singleton class.
For your usage i think you can follow the below steps,
make your constructor as private.
then, have a static function inside that class to return the instantiated object of your class.
you can have your own if(classobj==nul) check to verify if its already instantiated or not(only on first call it will be null , further calls it wont be null) and return the object.
Cheers :)

Yet Another Query About the Thread Safety of a (Java) Singleton

Consider the following:
public class Singleton {
private static Singleton instance;
// NO INSTANCE VARIABLES
private Singleton() {
super(); // Just to have something to write here.
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public String parseSomething(MyObject myObject) {
// Do stuff
}
public void doAnotherThing(String value) {
// Do something else
}
}
Are parseSomething() and doAnotherThing() thread-safe? In other words, if I have multiple threads getting the Singleton instance and making possibly simultaneous calls to those two methods, will it end lives?
My instinct (and limited experience) says "no," because those methods do not act on anything outside their scope; they do not carry state in any instance variables in Singleton. Each calling thread would have the parameters and locally-scoped variables in their own stack, so (in theory) they shouldn't collide.
Unfortunately, I can't seem to Google up any questions on this topic that don't involve some action by the instance methods on a state-carrying instance variable in Singleton.
Edit: Trying the instance thing again. My real question here, though, is, assuming N threads have a handle on the instance and are making calls to parseSomething() and doAnotherThing(), will they murder each other?
Are parseSomething() and doAnotherThing() thread-safe?
Highly depends, on what they do, and how they do it, singleton pattern, has nothing to do with thread safety, it supposed to guarantee that there is only one instance of the object in the running system, which by the way this implementation does not (You can create another instance of Singleton, using reflections, or if getInstance is called in parallel on getInstance call).
So, if this methods are stateless, and do not have any shared state, then they are thread safe. You can just make those methods static in your singleton class, and make a utility class out of this Singleton.

Java Singleton Design Pattern : Questions

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}

How do I make other classes derive from a singleton class?

I am sorry if this is a duplicate or too elementary, but how do I make a singleton class that can be subclassed?
Steve Yegge has an amusing article about singletons that mentions subclassing in this quote:
Then there's the subclassing thing.
It's almost impossible to subclass a
Singleton, and if you manage it, then
you shouldn't have been using a
Singleton in the first place. You
don't even want to go there. I've
walked roads that I dare not recount.
Just pretend you can't do it, and
you'll save yourself amazing amounts
of pain.
You generally can't, in any useful sense. This would be yet another reason to not use Singleton classes.
Actually, I don't think it is possible.
You make a class singleton by declaring its constructor(s) to be private. But if you then try to declare a subclass of your singleton class, the subclasses constructor wont be able to see the constructors of the superclass ... so they won't compile; e.g.
public class A () {
private A() { }
}
public class B () {
private B() { }
}
Both the Sun JDK 1.6 and Eclipse Ganymede compiler give a compilation error in the constructor B, to the effect that the no-args constructor for A is not visible.
You could increase the visibility of the private constructors, but then there is nothing (apart from good sense) stopping someone from creating multiple instances of it. In other words it is not really a singleton class anymore.
EDIT: I guess a kosher alternative would be to define a tree of one or more abstract (non-singleton) classes with the methods / members that you want to be common, and then define multiple singleton classes as a leaf classes as appropriate. But that is NOT one singleton class subclassing another one.
If you have defined your singleton as:
public class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Singleton() {
}
}
Then you can just do:
public class NewSingleton extends Singleton {
}
But, you won't be able to use the private methods so if you want to use the singleton you will still need to call Singleton.getInstance(); so you gain nothing by extending it.
But, there is no reason why you can't do it.
Now, if you want to add more functions to the Singleton class then you can use inter-type aspects from AspectJ and just inject new methods/properties into the Singleton which could then be used by the Singleton.
Singleton limits instances not the inheritance. Well - as already been pointed out it limits usefulness of inheritance and then you can relax private constructor to packaged or protected (which you may argue diminishes singletoness of the singleton) But what is the purpose?
As others have replied already, the uses of singleton subclassing are small. If you need a strategy pattern in the context of a singleton, you could define an interface and delegate to an implementation of that interface in the singleton instance. This moves the problem one layer down and makes it more clear why you would want to do it.
To answer your question; assuming the choice for the particular subclass your application uses is defined in for instance the system properties, you can do something like:
public static synchronised Singleton getInstance() {
if (instance == null) {
String clsName = System.getProperties().getProperty("singleton.class");
if (className == null || 0 == clasName.length()) {
instance = new Singleton();
} else {
Class cls = Class.forName(clsName);
instance = (Singleton) cls.newInstance();
}
}
return instance;
}
Disclaimer: untested code, add exception handling, etc :-)
Btw, make sure your getInstance() method is synchronised.

Categories