I've recently come across this kind of code somewhere.
package com.singleton;
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
System.out.println("Done creating Singleton");
}
}
Now, problem in this might not be apparent at first glance. Atleast not to me :p
so, adding this function makes the problem clear enough
public void print() {
System.out.println("Printing inside Singleton Variable");
singleton.print();
}
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
obj.print();
System.out.println("Done creating Singleton");
}
Now, running the program would result into a StackOVerflowError
My question is, There already was this one object inside another kind of pattern in the code. so why it didn't resulted into a StackOverflowError in first case.(i.e. before addition of print function and calling it in main class.)
The source of your confusion is that you think the singleton definition is recursive. It isn't, actually.
private static Singleton singleton = new Singleton();
This is a definition of a static field. This means that this field does not exist inside any instance of Singleton. It is associated with the Singleton class, and initialize at the loading of the class.
If this was not a static call, then you would be right. Creating an instance would create a new field which would create a new instance which would create a new field.
But for a static field, initialization is done only once, at the loading of the class. It then calls the constructor of the class, and that's it - no more creations of Singleton, no more initialization, and no self-reference.
So this example will cause a StackOverflowError:
public class Test
{
public Test test = new Test();
public Test() {
}
public static void main (String[] args ) {
System.out.println( new Test() );
}
}
And this is because the field test is not static but an instance variable, and thus its initialization is done when a new instance is created, and in itself create a new instance and so on.
Change the definition of test to static and the error will go away.
Two different scenarios here. Singleton's singleton will be initialized just once when Singleton class itself would get loaded. Hence when you will call getInstance on singleton, it wont reinitialize itself, rather it would return the same instance again and again.
Your second example is a recursive call which call's to itself without any exit condition in it and hence leads to StackOverflowError.
You may also confusing an object relationship that is recursive:
class Foo {
private Foo foo;
Foo(){ ... }
public void setFoo( Foo foo ){
this.foo = foo;
}
}
with a dynamic recursion of a method.
There is no problem with classes like Foo if they are constructed without running into a recursion of the other kind, e.g.,
Foo(){
this.foo = new Foo(); // Ooops!
}
In your first code case, static Singleton singleton = new Singleton(); was initialized when the Singleton class loaded, every time of calling Singleton.getInstance(); just returns the variable only.
In the second code case, there exists an infinite loop call, This will cause the JVM to allocate stack frames for space indefinitely, and each stack size is limited after allocating, according to the Java Virtual Machine Specification
If the computation in a thread requires a larger Java Virtual Machine stack than
is permitted, the Java Virtual Machine throws a StackOverflowError.
so this must result in a stackoverflowerror obviously.
Related
Following is double-check implementation of singleton pattern. Thread A is executing line test=new Test(); But just at the same time, thread B first checks the value of test. What's the value of test as for thread B?
class Test {
private Test test;
private Test() {
}
public static Test get() {
if (test == null) { // Thread B. When object is being created,
// what's value of test. Is it always null before
// Thread B new object?
synchronized (test.getClass()) {
if (test == null) {
test = new Test(); // Thread A. This thread is creating object.
}
}
}
return test;
}
}
Added
If it's not a right version of singleton pattern, can volatile keyword solve the problem? That is, private volatile Test test;
It is unknown. That is why this implementation is considered wrong.
There is possibility that test = new Test() first create object then assign reference to it to test and only then initialize it.
So thread B will have reference to object, but it may be not initialized.
This one also seems to be a good approach as suggested by Bill Pugh to eliminate the drawbacks of double check locking (as mentioned in the question) and we don't need to do eager initialization as well to eliminate this :
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.
This is one of the most widely used approach for Singleton class as it doesn’t require synchronization.
If it's not a right version of singleton pattern, can volatile keyword
solve the problem?
Indeed, this :
private Test test;
should be declared :
private volatile Test test;
Otherwise the memory of the thread B may keep a stale version of test that may be null while the thread A valued it with the private constructor.
By specifying test as volatile, you ensure that any assignment on it performed by one thread will be visible by other threads.
Now this way of implementing a singleton is not very straight (double conditional statement plus explicit synchronization).
As two fine alternatives, you could use the enum singleton idiom :
public enum Test implements TestInterface{
SINGLETON;
...
}
Note that the interface is advised to write a naturally testable implementation and to be able to switch to other implementations.
or else the Bill Pugh singleton idiom (here is in the eager flavor) :
public class Test{
// executed as soon as the T class is loaded by the classLoader
private static Test instance = new Test();
private Test() {
}
public static TestgetInstance() {
return instance;
}
}
I'm confused about an essential thing in java.
public class InitItself1 {
public InitItself1(){}
private InitItself1 me = new InitItself1();
}
Of course I know that the StackOverFlowError will be occurred when creating an instance of the above class. The above class will be initiated recursively itself because of the initiation of the variable "me".
But,
public class InitItself2 {
public InitItself2(){}
private static InitItself2 me = new InitItself2();
}
Of course the outcome of the above class, "InitItself2" is different to the prior class, "InitItself1". This works just fine, no error occurred. As I know, initiating static variables and executing static blocks are performed when classes in which static variables and blocks are loaded.
What makes me confused is that I think it's the same that the variables, "me" of both classes, "InitItself1" and "InitItself2" are initiated, and also they have references to their classes in which they are, so it looks that "initiating recursively" would happen in initiating both classes.
What is the point that I'm missing?
Good answer please.
Thanks :)
You are not going to get StackOverFlowError in the second case. As you have said yourself, static variables are initiated when the class is loaded, and because a class is only loaded once, the static InitItself2 me will only be instantiated once. Creating a new object with constructor doesn't require the class to be reloaded.
public final class InitItself {
static {
System.out.println("Class is loaded");
}
private static InitItself me = new InitItself();
static {
System.out.println("me is instantiated");
}
public InitItself() {
System.out.println("Constructor called, me=" + me);
}
public static void main(String[] args) {
System.out.println("START");
InitItself i = new InitItself();
System.out.println("FINISH");
}
}
Gives the following output
Class is loaded
Constructor called, me=null
me is instantiated
START
Constructor called, me=oop.InitItself#6ff3c5b5
FINISH
I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}
Seems like a very basic query but I was pondering how the static method main() below is able to execute a non static method(the constructor obviously) from it using the new keyword. Though I understand that new brings onto the table a few other things as well but how should I convince myself that this isn't an exception to the rule that static and non static methods can't using non static and static context respectively?
Below is the sample code:
public class ConstructorTest {
ConstructorTest(String str)
{
System.out.println("Constructor Printing "+str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorTest cnst=new ConstructorTest("here");
}
}
The above code actually prints --> Constructor Printing here
or in other words executing the body of a Non static method from a Static method?
Any plausible explanations are welcome.
The Java Tutorial states that
[...] Constructors are not members.
Therefore, there is no problem in calling them, since they are not bound to instances of your class. This would not make sense - hence, you cannot do the following:
Thing thing = new Thing();
Thing anotherThing = thing.Thing();
A constructor is not a method, so you cannot apply "method logic" to them.
In case you want to know more, the whole instantiation process is very well documented in the JLS. See 12.5. Creation of New Class Instances.
Actually constructor is compiled into the static method, this is how JVM internally creates instances of classes.
You are executing non-static code, but you are not doing it in a static context.
for instance:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
do();
}
}
This can not work, since do is an instance method, which might run code that is specific to the instance. So, how would the VM know which instance to use, or what value x should have?
Now, to first use a constructor, which is possible from any context:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
C1 t = new C1();
t.do();
}
}
Here, even though you are calling the method from within a static method, you are using it through an instance, so not in a static context.
ConstructorTest is not a method.
its an constructor,and you can use the constructor for initialize class property.
you can also initialize the static variable from the constructor like that :-
public class XYZ
{
static int i=0;
public XYZ() {
i=1;//not an compile time error
}
public static void doSome(){}
public static void main(String[] args) {
}
}
On a formal language level you should read the line
ConstructorTest cnst = new ConstructorTest("here")
as a class instance creation expression. As a matter of fact, this is not a call to a constructor or any other method.
The instance creation does many steps, like allocating memory for the new object, initializing the fields, calling constructors and initializer blocks. See JLS §12.5 for a detailed step-by-step description. Thus being said, the constructor invocation is only a part of the instance creation.
Additionally, you might see constructors as being static parts of the class. In fact, constructor declaration are not members (see JLS §8.8) and thus they are not overridable (as static methods also). Beware: This is only half true. When being inside the constructor you already have the instance created, and you are able to call other instance methods and/or access instance fields.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Efficient way to implement singleton pattern in Java
I was reading this Best Singleton Implementation In Java, but its not thread safe.
As per wiki :
if(singleton==null) {
synchronized(Singleton.class) { //
this is needed if two threads are
waiting at the monitor at the // time
when singleton was getting
instantiated if(singleton==null)
singleton= new Singleton(); }
}
But Find Bugs utility gives two errors in this :
1. Double null check.
2. Incorrect lazy initialization of static field.
What is the best way,
Is it Correct :
synchronized (Singleton.class) {
if (singleton== null) {
singleton= new Singleton();
}
}
The most efficient/simplest way to make a lazy loading Singleton is just
enum Singleton {
INSTANCE
}
Note: there is no need for locking as class loading is thread safe. The class is final by default and the constructor cannot be called via reflection. The INSTANCE will not be created until the INSTANCE, or the class is used. If you are worried the class might be accidentally used you can wrap the singleton in an inner class.
final class Singleton {
private Singleton() { }
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
IMHO, you have to be pretty paranoid to consider this a better solution.
A lot has been written about this issue. Yes, the simple double-check-locking pattern is not safe. But you can make it safe by declaring the static instance as volatile. The new Java Memory Model specification adds some code-reordering restrictions for compilers when dealing with volatile, therefore the original risks are gone.
Anyway, I rarely really need this kind of lazyness when creating the instance, so I usually simply create it statically at class-loading time:
private static MyClass instance = new MyClass();
This is short and clear. As an alternative, if you really want to make it lazy, you can take advantage of the class loading characteristics and do this:
public class MyClass {
private static class MyClassInit {
public static final MyClass instance = new MyClass();
}
public static MyClass getInstance() {
return MyClassInit.instance;
}
...
}
The nested class will not be loaded until the first time you call getInstance().
The first code sample in the accepted answer for Efficient way to implement singleton pattern in Java is thread safe. The creation of the INSTANCE is performed by the class loader the first time the class is loaded; it's performed exactly once, and in a thread-safe way:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
(copied from What is an efficient way to implement a singleton pattern in Java?)
The 2nd code sample in the question is correct and thread-safe, but it causes synchronization on each call to getInstance(), which affects performance.