Related
I'm following this tutorial for create Singleton and the owner have comment when the method below http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
If your singleton class is not using a lot of resources, this is the
approach to use. But in most of the scenarios, Singleton classes are
created for resources such as File System, Database connections etc
and we should avoid the instantiation until unless client calls the
getInstance method.
The Problem Is:
They say we should avoid the instantiation until unless client calls the getInstance method
BUT as I know in this code the instantiation (of object instance) always happened when class EagerInitializedSingleton load, and EagerInitializedSingleton just only load when we call EagerInitializedSingleton.getInstance()
=> The instantiation will happened on time with getInstance() and never before getInstance()
Reference:
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
(from https://stackoverflow.com/a/8704607/5381331)
So when are classes loaded?
There are exactly two cases:
- when the new bytecode is executed (for example, FooClass f = new FooClass();)
- and when the bytecodes make a static reference to a class (for example, System.out)
(from http://www.javaworld.com/article/2077260/learn-java/learn-java-the-basics-of-java-class-loaders.html)
Am I wrong or correct. Please give me some sugestion.
In this case with that specific code, you are probably correct.
However, if you had static methods of EagerInitializedSingleton, or static non-final members of EagerInitializedSingleton referenced somewhere in your code base prior to the invocation of getInstance, the instance variable of EagerInitializedSingleton would initialize.
Same with a reflective invocation of Class.forName on your EagerInitializedSingleton class.
Note (and forgive the obvious here) that there are alternative ways of declaring a singleton, including lazy-initialization or enums.
I think the problem is when a class gets loaded without the need to get the instance, but for some other reason. You assume that class will be used the first time when user will want to get an instance of that singleton, but it may happen for some other reason, he may just call a class loader for something, or use some 3rd party software to validate a class, anything that comes to mind that involves loading a class but not getting an instance of a singleton.
They say we should avoid the instantiation until unless client calls
the getInstance method
The solution is lazy loading.
From wikipedia, Initialization-on-demand holder idiom
When the class Something is loaded by the JVM, the class goes through
initialization. Since the class does not have any static variables to
initialize, the initialization completes trivially. The static class
definition LazyHolder within it is not initialized until the JVM
determines that LazyHolder must be executed. The static class
LazyHolder is only executed when the static method getInstance is
invoked on the class Something, and the first time this happens the
JVM will load and initialize the LazyHolder class.
public class Something {
private Something() {}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
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.
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.
I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one can create two methods with the same name in two different classes that won't clash with each other?
Also, I don't understand why I can't create a static constructor.
Could anyone help explain this concept?
Java has [static constructors] static initialization blocks which can be viewed as a "static constructor":
class Foo {
static String Bar;
static {
// "static constructor"
Bar = "Hello world!";
}
}
In any case, the only method in the main class which must be static is the main method. This is because it is invoked without first creating an instance of the "main class". A common technique, and the one I prefer, is to quickly get out of static context:
class Main {
int argCount;
// constructor
public Main (String[] args) {
// and back to boring ol' non-static Java
argCount = args.length;
}
void runIt () {
System.out.println("arg count: " + argCount);
}
// must be static -- no Main instance created yet
public static void main (String[] args) {
Main me = new Main(args);
me.runIt();
}
}
Also, static has nothing to do with "name clashes". A static method (or variable) is simply a method (or variable) that is not associated with a specific instance of a type. I would recommend reading through the Classes and Objects Java Tutorial and the section Understanding Instance and Class Variables.
Happy coding.
I am sharing one of the reason "why not a java constructor be static".
Simply to say, "A java constructor is always non static" because,
The purpose of the constructor is only to initialize/construct the object, and to make inheritance possible. To do these we need to use the two useful java keywords (cum non-static variables) such as this and super.
We will use 'this' to initialize the object.
We/Java will use super(ofcourse super()) to invoke super class constructor so that super object(or Object class) created first then the child object(hence the inheritance)
If the constructor is static then we cant use that two keywords(non-static variables) inside the constructor(As we know non-static stuff cant be referenced from static context)
So java constructors should not static.
Static methods belong to a class, not an object. The main method must be static because it is called first, before any other code has executed to instantiate any objects. It provides an entry point to the program. Static methods are called from outside of the container of an object. The same is true of static class variables. Only one copy exists for the entire class, as opposed to a member variable, which is created once for each object created from a class. They are used to store data for the class, such as the number of object instances have been created and not destroyed. This data belongs with the class. A good example of a static method is in the singleton pattern, where the constructor is private and can only be accessed by a static member function. A function outside the class would be unable to replicate this functionality. This method acts on class data and objects, so logically belongs to the same class. This all boils down to encapsulation. A class is responsible only for itself and knows only itself.
On the other hand, object methods are meant to operate on the data associated with a single instance of a class, an object. Constructors are the code that is used to initialize an object and set it's data to an initial state. They are executed immediately (and automatically) after the memory has been allocated to store a new object. Even if you do not explicitly define a constructor, a kind of "default constructor" is executed in order to map the object's member variables and the object's method code to the new object.
Hope this helps.
Constructor is used to create Objects.
Static is generally which is same for all objects.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Static methods only reference to static variables. Therefore all the initial parameters which you are giving to create an object would change for all objects. It is no point creating similar objects for no use.
Hope this helps.... :)
Constructor is the property of an object while static has nothing to do with object. That's why there is nothing like static constructor. But we have static block to do the similar task as constructor i.e. initialization of fields etc.
On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:
²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.
A little bit more context.
... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²
This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.
It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.
Hope it helped!
Constructors are neither entirely static (class level) or entirely non-static (instance level).
Unlike instance methods, constructors are not inherited.
Unlike static methods, a constructor can refer to this.
So, why can't you declare a constructor static?
Well, my take is that a (redundant) static keyword would be confusing and would not serve any purpose. Therefore they decided not to allow it.
The explanation that static initialization blocks can be viewed as constructors is (IMO) conceptually wrong. (It is analogous to saying that an instance initialization block is a regular constructor. Which is equally wrong.)
The key distinctions between static initialization and construction1 are:
static initialization happens at an indeterminate time2; there is no equivalent to new for class initialization,
there is no straight-forward way to pass (constructor) parameters to the initialization code
there is no practical way to recover from errors occurring during static initialization.
1 - Hypothetically, if class initialization was explicit, then it would make sense to have static constructors. But the downsize would be that applications would need to explicitly "construct" all of the classes that they used ... which would be horrible.
2 - You have a degree of control if you load a class dynamically, but even then if the class has already been loaded and initialized in the current classloader, then attempting to control initialization will fail.
I do not understand why the main method has to be static.
It has to be if you want the main method to act as an entrypoint for your application.
The problem is that if main was an instance method, then there would need to be an instance of your entrypoint class to call the main method on. But how do you create it? Which constructor would you choose? What if there was no public constructor?
The bottom line is that this is the way that Java was designed ... back in the 1990's ... and so far they have not seen the need to change this.
a) static is belongs to class not object and constrictor is called during the object creation.
b) if we create a constructor as static then it can't be call by subclass as static is accessible only from class not by sub class. So during subclass object creation it can't be call the present class constructor.
c) static members are executed first in the program, so if we declare constructor as static then it will executed before object creation which is oppose the purpose of the constructor.
If we declare constructor as static then it will give compile time error.
If we want to initialize static member then need to use of static block.
I wrote a simple example as an answer to a related question yesterday which may help make things more understandable: what's the point of java constructor?
The point of Static methods is that they can be called without creating an instance of a class, while "normal" instance methods are related to an instance, and can not be called without one.
Since the Main method of the Main class is the entry point of the program, no instance can possibly have been created yet, so naturally, you can not access it via an instance. Therefore, it is Static, so it can be run as the start of the program.
Just take a look on this link, it will definately help you to understand:
Why can't make a constructor static?
AND
Constructor is called at Run-time when we create Objects.
Static is same for all objects but all objects have their own state and properties.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Note: static is class level while constructors related to the objects.
e.g.
public class Foo
{
String name;
int id;
// define constructors
Foo (String name, int id)
{
this.name = name;
this.id = id;
}
p s v m(String[] arg)
{
Foo f1 = new Foo("Amit",001);
Foo f2 = new Foo("Rahul",002);
}
}
If we create static constructor then both objects(f1 also) will contain the last updated value regarding name and id as Rahul and 002.
A constructor cannot be static, because in an OO language, the process for creating an object is as follows:
allocate the object
call the constructor to initialise the newly-allocated object
Constructors are not used anywhere else (and a type-safe language should enforce this), so it follows that a constructor will always be called in a non-static context.
If a constructor were static, it would not receive a reference to the newly-allocated object, and thus would not be able to initialise it.
Thus, a constructor can always be non-static (as it is always called from a non-static context) and must always be non-static (otherwise it would be unable to perform its task).
The main(String[]) method has a specific prototype that is dictated by how the Java runtime environment works. When you invoke java MyApplication from the command line, the Java VM will look for a static main(String[]) method contained in that class in order to execute the application. If that method is not found, then the Java VM can't run the class as an application. That's just how the language is defined. It also means that the Java VM doesn't create an instance of your application class in order to run it.
Now, if you want your class to be usable either as a standalone application or as an instance that's created by something else, then you can have your class implement the Runnable interface, and also provide a main method that executes the run method on a new instance.
public class MyRunnableThing implements Runnable
{
// Define whatever variables your runnable thing needs here as
// private instance fields.
/** Fulfills requirements of Runnable interface. */
public void run()
{
System.out.println( "I'm running..." ) ;
}
/** Also makes the class runnable from the console. */
public static void main( String[] args )
{
MyRunnableThing runMeNow = new MyRunnableThing() ;
runMeNow.run() ;
}
}
Now any class could potentially create an instance of MyRunnableThing and use its run() method to produce the same behavior that would have been seen by executing java MyRunnablething.
See also: Working with Static Constructor in Java. Some highlights from that Q&A:
A constructor is used to create an instance of the class, so it's an instance method, not a static method.
You can create a static method that creates an instance of the class, using the constructor. This is how the trendy new "builder" classes work.
You can create a static method that returns a persistent, unique singleton instance.
If your class has static members, then you can create a static initializer to initialize the values of those members.
The purpose of Constructor is to Construct an Object i.e. to initialize class's instance variables either their default values or by their initialized values. non-static Instance variables can't be accessed by static methods . So constructor is not static.
The method declared as static requires no object creation .As we don't create object for the main method it is declared as static.
constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
First, the key word static means that everything marked static must be the class-level thing and belongs to the class only.While constructors belong to object and they may usually be called when we use the new operator.So we now know that a constructor is not even a class property,how could we possibly mark it as static?
Second,static constructor violates the whole purpose of inheritance in java.Every time just before we create an subclass object ,JVM automatically calls the superclass constructor to make it ready for the subclass object to be created.But if we mark the constructor static,the subclass will not be able to access the constructor of its superclass because it's marked static thus belongs to class only.
Java does not permit to declare a constructor as static. Following are the reasons.
Static means for the same class. i.e, static methods cannot be inherited.
With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.
If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.
Static Belongs to Class, Constructor to Object
We know that static methods, block or variables belong to the class. Whereas a Constructor belongs to the object and called when we use the new operator to create an instance. Since a constructor is not class property, it makes sense that it’s not allowed to be static.
Is calling Class.getInstance() equivalent to new Class()?
I know the constructor is called for the latter, but what about getInstance()?
Thanks.
There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
In code,
Object instance = Object.class.newInstance();
is the same as
Object instance = new Object();
The Class#newInstance() call actually follows the Factory Method pattern.
Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.
Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.
See also:
Real world examples of GoF design patterns.
Absolutely (usually) not.
getInstance is the static method often used with the Singleton Pattern in Java. The new keyword actually creates a new object. At some point there must be a new (although there are a few other methods to instantiate new objects) to actually create the object that getInstance returns.
In the context of an abstract class, a getInstance() method may represent the factory method pattern. An example is the abstract Calendar class, which includes static factory methods and a concrete subclass.
Some abstract classes have getInstance() methods because you can't instantiate an abstract class by using new keyword.
Yes, this is often used in Singleton Pattern. It`s used when You need only ONE instance of a class.
Using getInstance() is preferable, because implementations of this method may check is there active instance of class and return it instead of creating new one. It may save some memory. Like in this example:
public static DaoMappingManager getInstance() {
DaoProperties daoProperties = null;
try {
daoProperties = (DaoProperties) DaoProperties.getInstance();
} catch (PropertyException e) {
e.printStackTrace();
}
return getInstance(daoProperties);
}
public static DaoMappingManager getInstance(DaoProperties daoProperties) {
if (instance == null) {
instance = new DaoMappingManager(daoProperties);
}
return instance;
}
For start:
newInstance() is a static method. This means you can access to it without creating new class directly! And it creates that class itself "with necessary inits" (via an inner new myClass()). This means you can add some newInstance methods (newInstance4usage1, newInstance4usage2,...) for different needs that per static method creates class with different initialization.
Sometimes, this helps class's user (final programmer) to creating class without any worry and very comfortable.
This helps really when the init process is complex or has important or or usual levels. this method don't prevent from creating class by new keyword.
I like it!
Excuse me for slow answering, I am typing with my mobile phone!