The instantiation happened before getInstance() or when getInstance()? - java

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;
}
}

Related

When static variable be instantiated in Android

For example, I have a class
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
And my application have 2 activity A.java and B.java (from A I can go to B).
In B activity I have
import EagerInitializedSingleton.java;
public class B{
onCreate(...){
EagerInitializedSingleton.getInstance()...
}
}
My question is when instantiated be instantiated`
When launch application (before A Activity start)
When import EagerInitializedSingleton.java
Or when EagerInitializedSingleton.getInstance()
If possible, can I check when be instantiated by write Log or something?
Any help would be great appreciated.
UPDATE
I'm follow here to create EagerInitializedSingleton
http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
And they have say
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
Like some answer say that instance be instantiated when I call EagerInitializedSingleton.getInstance()..., so who is correct?
static variables are initialized when the classloader loads the class for the first time, either through static reference or instance creation. It will be shared across all instances of the class. And remember, it will be initialized before any instance creation of the class.
So, in your question:
When launch application (before Activity start)
No
When import EagerInitializedSingleton.java
No
When EagerInitializedSingleton.getInstance()
Yes
Or whenever you make a static reference to the EagerInitializedSingleton class.
Edit - Just to clear things out as per comments:
Call to getInstance() will not result in instance creation. But the static reference to the class does as the class loads for the first time.
When you call EagerInitializedSingleton.getInstance()
For starters, this is not a proper singleton implementation. Your constructor, or lack of one, will allow the user to use the default empty constructor and create more objects of that class. Check out how to implement it here or anywhere you find online.
The question you asked has nothing to do with android, it's a plain Java question, having to do with static variables initialization. You can find the answer to that question here.

Correct implementation of initialization-on-demand holder idiom

I have got two versions of "Initialization-on-demand holder idiom":
http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
The major difference between above is that the first one declared INSTANCE as private, but the second one declared INSTANCE as public.
Please tell me which one should I use.
Sorry, I have not found the difference between using private and public in my application:
public class Singleton {
private int x;
public int getX() {
return x;
}
private Singleton () {}
private static class LazyHolder {
//both private and public works
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
The only thing I do is to call something like Singleton.getInsance().getX(), so both versions works.
Thus I want to know the situations for using them.
There are several things to explain about singletons and the initialization-on-demand holder idiom. Here we go:
1) The access modifier:
Normally you can't access fields and methods in another class if they are private. They must at least be package private (having no modifier, it is) if the accessing class is in the same package. So the correct way to implement it, would be:
public class Singleton {
...
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
However, JLS 6.6.1 explains:
Otherwise, if the member or constructor is declared private, then access is
permitted if and only if it occurs within the body of the top level class (ยง7.6)
that encloses the declaration of the member or constructor.
That means, declaring the field INSTANCE as private still allows the access from inside the top level class Singleton. But the compiler must do some tricks to get around the private modifier: It inserts package private methods for getting and setting such a field.
In fact, it does not matter, which modifier you place on it. If it is public, it still cannot be accessed from other classes than Singleton. However ... I think the package private access is the best. Making it public does not makes sense. Making it private forces the compiler to do some tricks. Making it package private reflects what you have: Access to a class member from another class.
2) How to implement a singleton:
If you ever want to consider serialization, the singleton implementation will get a bit difficult. Joshu Bloch wrote a great section in his book "Effective Java" about implementing singletons. At the end, he concluded to simply use an enum for this, as the Java enum specification provides every charecteristic that is needed in regards to singletons. Of course, that does not use the idiom anymore.
3) Considering design:
In most design decisions, singletons do not have their places anymore. In fact, it could indicate a design issue, if you must place a singleton into your program. Keep in mind: Singletons provide a global acess mechanism to some data or services. And this is not OOP.
private static class LazyHolder {
$VISIBILITY static final Singleton INSTANCE = new Singleton();
From a consumer's point of view it does not really matter if $VISIBILITY is public or private because the LazyHolder type is private. The variable is only accessible via the static method in both cases.
I use number 1 (private INSTANCE) because you generally try to use the narrowest scope as possible. But in this case since the Holder class is private it doesn't really matter. However, suppose someone later decided to make the Holder class public then number 2 could be problematic from an encapsulation perspective (callers could bypass the getInstance() method and access the static field directly).

Difference between loading a class and instantiating it

Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same time the Class get loaded? After all static code is part of the class rather than it's individual instances. It would be helpful if someone provided an example to help me understand this better.
Here is some nice explanation(with an example and observation)
When a class is loaded and initialized in JVM - Java
When Class is loaded in Java
Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.
When a Class is initialized in Java
When a Class is initialized in Java
After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :
1) an Instance of class is created using either new() keyword or
using reflection using class.forName(), which may throw
ClassNotFoundException in Java.
2) an static method of Class is invoked.
3) an static field of Class
is assigned.
4) an static field of class is used which is not a
constant variable.
5) if Class is a top level class and an assert
statement lexically nested within class is executed.
Hope that helps.
Integer.toString(123);
For the above static method call to work, the Integer class must be loaded.
Integer i = new Integer(123);
And in the above code, I've created an instance (object) of the Integer class (which must also be loaded for this to work, obviously).
Some classes are not meant to be instantiated (like the Math class, for example, which only has static methods).
Class loading
Whenever the JVM determines it needs a class (to use its static variables, to create a new object, to use its static methods etc) it will load the class and static initialisation blocks will run, static variables are initialised etc. This is (at least under normal circumstances) done only once
SomeClass.someStaticMethod(); //SomeClass is loaded (if its not already)
SomeClass.someStaticVariable; //SomeClass is loaded (if its not already)
SomeClass var=new SomeClass(); //SomeClass is BOTH loaded (if its not already) AND instantiated
As a result the following runs (as an example):
static Vector3d var=new Vector3d(); //static variables are initialised
static{
//static initialisation block are run
}
Instantiating a class
On the other hand you instantiate a class when you create an instance of the class with the new keyword; instantiating a class is creating an object of the class.
SomeClass var=new SomeClass(); //SomeClass is instantiating (and loaded if its not already)
As a result the constructor runs:
public SomeClass(){
}
and
{
//initialisation block(s) also run (but these are very uncommonly used)
}
Class loader actually loads byte code into JVM , runs static initializers.When you want to use static fields within class without creating instance of it ,class must be loaded by class loader first.Default classloader in java is java.lang.ClassLoader.This class loading is done only once.
While class instantiation is creating instance of class into memory.We can instantiate class using new.Class instantiation can be done as many times.
eg: Animal a=new Animal();
More on class loading
A class is loaded when it is referenced (e.g. by Class.forName()).
You instanciate an object by creating an instance, e.g.
Object o = new Object();
You can also instanciate an object by using reflection.
static members of a class are instanciated when the class is loaded, e.g.
public class Sample {
private static int variable = 10;
}
When I now load the class (e.g. by Class.forName("Sample");) Then the variable variable is initialized with the value 10.
If you are creating a new instance of a class and it is not loaded before the class will be loade before (atomatically). So the construct Class.forName() is only needed under special circumstances (if the class is not known by compile time e.g.).

Can objects have access modifiers?

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.

Are Java static initializers thread safe?

I'm using a static code block to initialize some controllers in a registry I have. My question is therefore, can I guarantee that this static code block will only absolutely be called once when the class is first loaded? I understand I cannot guarantee when this code block will be called, I'm guessing its when the Classloader first loads it. I realize I could synchronize on the class in the static code block, but my guess is this is actually what happens anyway?
Simple code example would be;
class FooRegistry {
static {
//this code must only ever be called once
addController(new FooControllerImpl());
}
private static void addController(IFooController controller) {
// ...
}
}
or should I do this;
class FooRegistry {
static {
synchronized(FooRegistry.class) {
addController(new FooControllerImpl());
}
}
private static void addController(IFooController controller) {
// ...
}
}
Yes, Java static initializers are thread safe (use your first option).
However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.
This is a trick you can use for lazy initialization
enum Singleton {
INSTANCE;
}
or for pre Java 5.0
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton instance() {
return SingletonHolder.INSTANCE;
}
}
As the static block in SingletonHolder will run once in a thread safe manner you don't need any other locking. The class SingletonHolder will only get loaded when you call instance()
In usual circumstances everything in the static initialiser happens-before everything that uses that class, so synchronisation is not usually necessary. However, the class is accessible to anything that the static intiailiser calls (including causing other static initialisers to be invoked).
A class can be loaded by a class loaded but not necessarily initialised straight away. Of course, a class can be loaded by multiples instances of class loaders and thereby become multiple classes with the same name.
Yes, sort of
A static initializer only gets called once, so by that definition it's thread safe -- you'd need two or more invocations of the static initializer to even get thread contention.
That said, static initializers are confusing in many other ways. There's really no specified order in which they're called. This gets really confusing if you have two classes whose static initializers depend on each other. And if you use a class but don't use what the static initializer will set up, you're not guaranteed the class loader will invoke the static initializer.
Finally, keep in mind the objects you're synchronizing on. I realize this isn't really what you're asking, but make sure your question isn't really asking if you need to make addController() thread-safe.
Yes, Static initializers are run only once. Read this for more information.
So basically, since you want a singleton instance, you should do it more or less the old-fashioned way and make sure your singleton object is initialised once and only once.

Categories