I am using the java driver for mongodb, and the documentation says to:
"you should create a single Mongo instance, and you can use it in every request."
Using a single instance sounds like a singleton.
In other places for a different library I have read the instructions saying that I should create a static reference as it is thread-safe.
Can someone explain the differences between a singleton and creating a static reference?
So the actual code that I need to instantiate either statically or via a singleton would be:
Mongo m = new Mongo( "localhost" , 27017 );
Can someone explain both methods and the underlying differences if any?
In Java you typically use a static variable to implement the Singleton pattern.
http://java.sun.com/developer/technicalArticles/Programming/singletons/
Singleton is a design pattern where you have one instance of an object shared amongst the rest of your code. Static variables are a Java language feature.
In order to implement a Singleton, you would usually use static variables.
You have 3 issues: singleton, static reference and thread-safety.
You have a singleton if you can only create one instance of a class. That's useful since things would get messed up if you had two instances of Mongo running. However, you cannot implement the singleton design pattern for Mongo in your code: you can call new Mongo() anywhere you want and create as many instances as you want. You just have to be careful you don't do so, but it shouldn't be very hard.
To implement a singleton, the class designer will very often use a static reference as follows:
public class MyClass {
private static final MyClass SINGLETON = new MyClass();
private MyClass() {...} // !!private, not accessible
public MyClass getSingleton() { return SINGLETON; }
}
And you will only ever have one single instance of MyClass since the constructor is private and the only way to get an instance is through MyClass.getSingleton(). Obviously the Mongo designer would have had to design the Mongo class as such; there is nothing you can do to make it a singleton.
As far as thread-safety is concerned, I don't quite see the link with singleton. A singleton class must be made thread-safe: if many threads change and read the state of a singleton, you need proper synchronization to make sure all threads see the same values. I don't know Mongo, but I would bet it is a thread-safe class.
Use the Singleton pattern on an object if you only want to be passing around a single instance of this object to other objects and methods that need to use this single instance. Use a static reference if you only want to be using the object's class statically (i.e as a static reference).
If only one class is using your singleton object there is no visible difference in number of objects created.
Assuming you need an object of classASing using Singleton approach
ClassASing {
private static ClassASing obj = new ClassASing();
private ClassAsing(){...}
public static ClassASing getNewObject(){
return obj;
}
}
Using Singleton approach
ClassB{
private ClassASing singObj = ClassASing.getNewObject();
}
no matter how many instances of ClassB created all of them will be using the same object of ClassASing
using static reference
ClassB{
private static ClassA sObj = new ClassA();
}
* no matter how many instances of ClassB created all of them will be using the same reference pointing to the same object.
Not much difference here 1 object being used in both the cases.
Now if u consider another sencario that you need object in two of your classes.
singleton approach
ClassB1{
private ClassASing singObj1 = ClassASing.getNewObject();
}
ClassB2{
private ClassASing singObj2 = ClassASing.getNewObject();
}
no matter how many instances of ClassB1 created all of them will be using the same object of ClassASing
no matter how many instances of ClassB2 created all of them will be using the same object of ClassASing that ClassB1 is already using so only one object of ClassASing
Static reference approach
ClassB1{
private static ClassA sObj1 = new ClassA();
}
ClassB2{
private static ClassA sObj2 = new ClassA();
}
no matter how many instances of ClassB1 created all of them will be using the same reference sobj1 pointing to the same object
no matter how many instances of ClassB2 created all of them will be using the same reference sobj2 pointing to the same object but this object is different from the one created in ClassB1 so now you have two objects of ClassA.
Related
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 :)
I was going through a piece of code when I came across this:
public class ClassicA {
private static ClassicA instance = null;
}
I have never used such a thing and wanted to know what it means and how it is used. Also, what is the purpose of the access modifier for the object? Any examples/links are welcome.
It probably means that ClassicA is a Singleton. It is usually involved with declaring a private constructor, and a single public static getInstance() method.
Singletons are used when you want to make sure there is only one global instance of ClassicA in your entire application. Instead of instantiating it, you call getInstance(), which will check if it was instantiated once or not. If it was, it will instantiate it, and store the the resulting object in the private instance field. If it was already constructed, just return the instance field without re-instantiating.
Note that this is considered bad practice. See: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what
Well, the class ClassicA has a private and static field instance which is null.
If there are no getters/setters the only way to access that field would be using reflection.
Since this looks like a singleton, I guess there's a getter as well that returns instance and if it is null first creates an instance and assigns it to the field.
It's a (static) member of the class, and yes, these can have access modifiers. (And as others have noted, it indeed looks like a portion of a Singleton.)
its a singleton
basically the author intended there to be only 1 instance of this class alive (the instance field)
the constructor is probably private and used only within the class.
This is used typically for a class that exhibits the Singleton design pattern.
The point is that for these types of objects you only want a single instance at most. What you do is create a private constructor for the class and then usually a public static method called, getInstance in which you check if the private instance variable has been set yet or not. If it has not yet set, you create a new instance of the class and assign it to instance, then you return that instance. If the object was already created you simply return it. Like this:
public class MySingleton {
private static MySingleton instance=null;
private MySingleton() {
//do stuff
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Then from throughout your program you can easily get the singleton object from anywhere.
Thus, a singleton is effectively just a glorified global variable in languages such as PHP. I would argue though that it is a lot cleaner as you can prevent others from reassigning the reference to the instance and other trickery that may be very bad from a design standpoint.
Typically people use it for classes that manage some type of data access, such as a DB object, for Factory classes and builder classes, see this for more info
This is used for singleton pattern. See here
private static means that the instance is available to all the instances and static methods of the class, but only to them. It's actually like having static private method.
Such tricks can be used for example for implementing a singleton: you keep internally a single instance of a class, and you can give it to the class's clients on demand. Or for any other case when you need something shared just between the static methods and instances of some class.
Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Difference between static class and singleton pattern?
What is the difference between a Singleton pattern and a static class in Java?
HI
I am not clearly getting What’s the difference between a singleton class and a static class?
Can anybody elaborate this with example?
Singleton Class: Singleton Class is class of which only single instance can exists per classloader.
Static/Helper Class (Class with only static fields/methods): No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
Following is referenced from this blog "Static classes in Java" describes it nicely. The blog also has examples for explaining same:
Singleton example:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if (instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Static Class example:
/**
* A helper class with useful static utility functions.
*/
public final class ActionHelper {
/**
* private constructor to stop people instantiating it.
*/
private ActionHelper() {
// this is never run
}
/**
* prints hello world and then the users name
*
* #param users
* name
*/
public static void printHelloWorld(final String name) {
System.out.println("Hello World its " + name);
}
}
So what's the difference between the two examples and why do I think the second solution is better for a class you don't want or need to instantiate. Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.
Same answer is also referenced from my answer here
Old que/ans on SO : Difference between static class and singleton pattern?
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
The difference is not the correct way to ask.because singleton is not a keyword compared to static. you should be asking like "When to choose which one?". what are the advantages of singleton class over static class, these questions comes at the design stages.
Singleton:
Usage:
classes that serve as global configuration , ex: Trial version of software with one database connection, JDK Runtime classes instances per jvm.
When to go:
1.While developing your code,you think of forward compatibilty, like tomorrow when you need to convert this singleton class to normal class or allow subclassing.
2. You can provide lazy loading feature , when this singleton class is heavy.
static:
Usage:
classes that basically does conversions,utility functions. please check Math class.
When to go:
1. helper classes, used by all the classes in your api development.
disadvantage:
1. classes are eagerly loaded .
expecting points from other people.
It's the difference between a pattern and how the pattern is implemented.
The Singleton pattern is not tied specifically to the Java language. There may be different ways of making a class into a singleton, depending on the language you use. Many OO languages use the equivalent of static variables to make a singleton, but others might use different techniques.
Also, some ways of implementing a singleton are better than others. One good way of implementing a Singleton is to properly encapsulate access to that Singleton through a factory method:
public class Example {
private static final Example SINGLETON = new Example();
public static Example getInstance() { return SINGLETON; }
private Example() { /* Constructor */ }
}
Using this technique, you can do all sorts of sophisticated things: lazy-load the singleton, replace it with some subclass, manage the singletons initialation via configuration, and so forth.
A Singleton is not a type of a class but a design pattern. With Singleton you (try to) guarantee, that only one instance of a certain class is ever constructed inside a single Java Virtual Machine. Modern implementations of the singleton pattern use enums, by the way. Older implementations use a private constructor and store the reference to the single instance in a static field.
A static class is always a member class which, in contrast to an inner class, has no access to instance variables of the surrounding class.
Static class example
public class A {
public static class B {
}
public int notAccessibleForB;
public static int accessibleForB;
}
Singleton pattern (simple old style)
public final class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton(){}
}
Singleton pattern (simple modern style)
public enum Singleton {
INSTANCE;
}
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;
}
}