Suppose I have a class in Java like this:
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;
}
public void initialize(String id, Double num, String data){
....
}
}
What is the ideal method type for my ClassicSingleton if I will be accessing an "instance" of it in another class?
Should initialize be a static function so that I can just call this in other class:
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton = ClassicSingleton.initialize("id",0.0,"data");
or should I leave initialize as it is and call:
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton.initialize("id",0.0,"data");
If you are accessing instance then use the second option
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton.initialize("id", 0.0, "data");
initialize should be a static method. The idea of a Singleton is that it is the only instance of that object. If one object is initialized twice, or is initialized through an instance of that object, it slightly defeats the purpose of the Singleton pattern.
Personally, I like to call initialize in the constructor, which itself is only called once, to prevent any confusion.
If you are creating the instance of Singleton class then you should go for the second one
Related
I went through the wiki https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand Initialization on demand holder Idiom for Singleton pattern, though the wiki mentions how it's thread safe, it doesn't say how this actually ensures only one instance is created ever, i.e if in two different classes Something.getInstance() is called how do they have the same object ?
I am new to Java, so any help would be appreciated.
Basic pattern for a singleton:
//final so it can't be extended, not needed, but I like it for security
public final class MySingleton {
//Private so no other class can access it directly
//static so it stays resident in memory
//final so it can't be nulled out or reassigned;
//The constructor is called when the class is loaded.
private static final MySingleton instance = new MySingleton();
//The constructor is private so no more instances can be created
private MySingleton() {
}
public static final MySingleton getInstance() {
return instance;
}
//Alternatively, you could have the instance initialized to null
//and have creation when getInstance() is called
public static final MySingleton getIntance() {
synchronized(instance) {
if (instance == null) {
instance = new MySingleton();
}
return instance
}
}
Case 1:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {
...
}
}
Case 2:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
...
}
public static Singleton getInstance() {
return INSTANCE;
}
}
Is the second method the recommended way to implement the Singleton design pattern, because I have never seen the first one in any example for Singleton pattern.
Without going into all the stuff about singletons being an antipattern (but you should read up on it!), the currently best way to make a singleton in Java is to use an enum.
public enum Singleton {
INSTANCE;
}
The reason this is better is because the JVM guarantees that only one instance of the enum (per classloader) will exist at any time. It is thread safe, and you cannot use reflection to create another instance of the singleton.
Enum-values are also lazily instantiated, so you won't create the singleton before you access Singleton.INSTANCE the first time.
The best way to make a singleton is to use Enum.
public enum Foo {
INSTANCE;
}
What is an efficient way to implement a singleton pattern in Java?
In your example, case 1 is more simple, so it's better.
But just wonder what happen if your constructor function is more complicated with some parameters. At this time, you really need some thing like this:
public class Singleton {
private static final Singleton INSTANCE;
private Singleton(string a, string b, string c) {
...
}
public static Singleton getInstance(string a, string b, string c) {
if (INSTANCE != null) { //note in multiple thread env, need add synchronize here.
......
}
return INSTANCE;
}
}
The first process of creating Singleton object created the instance of Singleton class even before it is being used and that is not the best practice to use.
Also the same problem exists in second implementation.
My preferred way of singleton instance creation:
private static final Singleton INSTANCE = null;
public static Singleton getInstance(){
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
Above implementation of Singleton instance creation is okay in single threaded environment but in case of multi-threaded environment two threads may access if block at same time so they will have different instances. This could be solved as below:
private static final Singleton INSTANCE = null;
public static Singleton getInstance(){
if(INSTANCE == null){
synchronized (Singleton.class) {
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
Hope this helps.
This how I implement singleton with enum
import static collections.concurrancy.ConcurrentHashMapInstanceEnum.STAFF;
public enum ConcurrentHashMapInstanceEnum {
STAFF;
private ConcurrentHashMap<Integer,Person> concurrentHashMap = null;
private ConcurrentHashMapInstanceEnum() {
concurrentHashMap = new ConcurrentHashMap(10, 5f, 4);
}
public ConcurrentHashMap getConcurrentHashMap() {
return concurrentHashMap;
}
}
and this is how to reach in a thread...
staffList = STAFF.getConcurrentHashMap()
Yes Obviously the second method is preferred way to implement Sigleton pattern , Inside getInstance() you have to check if instance is already created then return the same and Only create new instance if there is No instance of the class.
Also Make getInstance method as static method.
I have a classic singleton implemented in java
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {} ;
public static ClassicSingleton getInstance() {
if (instance == null)
return new ClassicSingleton();
return instance;
}
}
I have the following driver
public class SingletonDriver {
public static void main(String[] args) {
System.out.println(ClassicSingleton.getInstance().toString());
System.out.println(ClassicSingleton.getInstance().toString());
}
}
The output is something like
ClassicSingleton#75e4f66a
ClassicSingleton#aede59e
I thought the output would be pointing to the same object. Shouldn't the values be the same?
Your implementation of getInstance() is wrong. You never initialize instance, and thus return a new instance on each invocation. If instance is null, you should save it to your data member, and only then return it:
public static ClassicSingleton getInstance() {
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
You forgot to assign new ClassicSingleton() to instance, so you actually have a factory instead of a singleton; you'll create a new instance on every call. (Note also, of course, that this isn't thread-safe.)
I have an assignment for school where I have to spot patterns in a certain given project. All is well (well, relatively..) but it seems that most patterns I find are some sort of variation. The singleton I had to find is no different.
The code is given below. The strange thing about this is that this class does not seem to instantiate with the following constructor, as one would expect:
public Singleton() {
if (singleton == null) {
singleton = new Singleton();
}
}
However, it is instatiated with this (as you can see in the original code below)? In my understanding this creates some sort of static singleton? I debugged and saw indeed that the first time the constructor is called by
Singleton x = new Singleton();
x.Print();
, it is indeed null. And this is a Singleton instance. However, shouldn't there be
private static Singleton singleton = new Singleton();
on top of the class instead of singelton = this;?
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
return singleton;
}
/**
* The constructor.
*/
public Singleton() {
if (singleton == null) {
singleton = this;
}
}
public void Print()
{
System.out.println("I'm a singleton!");
}
}
I'm pretty sure it is indeed a singleton, it's just of the type I have never seen and I don't get reasoning behind it, that's what I'm basicly asking.
There is generally two approaches to creating a Singleton class, both are based on keeping the constructor private.
The first approach:
public class Singleton
{
public static final Singleton INSTANCE = new Singleton();
private Singleton{...}
}
You create an instance like this: Singleton single = Singleton.INSTANCE;
The second approach:
public class Singleton
{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){...}
public static Singleton getInstance(){ return INSTANCE; }
}
In this case, you create an instance like this: Singleton single = Singleton.getInstance();
The getInstance() method is then regarded as a public factory method.
As you can see, in both cases the new keyword is definitely used to create a single instance of the class, but because of the pattern used, there can only be one instance and no more. You don't need to use the "this" keyword.
Hope this helps.
Your code has not followed the Singleton pattern. I have shown below a class following the Singleton pattern. this refers to the current object instance. When you initialize the singleton reference with this inside constructor, it calls the default (no-args) constructor and assigns it back to the this reference and then it is assigned to singleton class member variable
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
/**
* The constructor.
*/
private Singleton() {
System.out.println(singleton);
if (singleton == null) {
/*this will call a default constructor
*and instantiate Singleton object
*/
singleton = this;
}
}
public void Print() {
System.out.println("I'm a singleton!");
}
public static void main(String[] args) {
Singleton singleton = Singleton.getDefault();
System.out.println(singleton.Print());
}
}
Hope you can understand!
I think you are confusing the meaning or this. this is not instantiating the class, this references the newly created instance. Then whenever someone calls your constructor a new instance is created (and returned) no matter you store in private static Singleton singleton; or not.
As well said #dic19 you must make your constructor private for preventing more than one instance to exist.
If the point is not to modify the code as you said, then the point is to report that this class is NOT a singleton.
You can check debugging:
Singleton x = new Singleton();
Singleton x1 = new Singleton();
Singleton x2 = new Singleton();
You will see all three are different instances, being Singleton.getDefault() simply the first you created.
If we use singletone we do not need to create instance for use. Because when we are creating singletone then we are creating new instance if not created.
Take a look of below code :
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void testSingleTone(){
System.out.println("test");
}
public static void main(String[] args){
Singleton.getSingleton().testSingleTone();
}
}
Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}