I have a queston regarding double-checked locking.
Consider this example:
public class Singleton {
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
As I have understood, the above code is the correct way to make a Singleton class.
However, NetBeans wants me to remove the outer if statement, so it would look like this:
public class Singleton {
private static volatile Singleton instance = null;
public static Singleton getInstance() {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
return instance ;
}
}
The only differece between these two snippets is that in the second example, the code will always get into the synchronized block and in the first it will not. Why would I listen to NetBeans and remove the outer if statement? It should be better avoid the locking.
NetBeans's automatic hint system obviously isn't aware that it's possible to do double-checked locking correctly with volatile, as you've done, so it suggests full locking instead. Better safe than sorry. But you're right in this case, not NetBeans.
Most of the time, the singleton will be used, and doesn't cost much to create, so just make it simple:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
...
}
If you really want lazy instantiation, use a static inner class:
public class Singleton {
public static Singleton getInstance() {
return Holder.INSTANCE;
}
...
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
}
Don't listen to NetBeans in this situation. Your first code sample is correct.
Related
I have a singleton class and I added the msg method but I'm not sure if is okay to add it to the singleton class or not
public class Singleton {
private static Singleton single_instance = null;
private Singleton() {
}
public void msg(String msg){
System.out.println(msg);
}
public static Singleton getInstance() {
if (single_instance == null) {
single_instance = new Singleton();
}
return single_instance;
}
}
Singleton is a Creational Design Pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Aside from that, it is just an ordinary class that can have as many public methods as will need to satisfy the requirements for which it was designed.
Singleton objects can mutate (change the value of its internal attributes - variables), or can be immutable (for example, Java enums can be used to create Singleton instances).
Using your class as an example, you can do something like this and be perfectly legal:
public class Singleton {
private static Singleton single_instance = null;
private String message = "none";
private Singleton() {
}
public void showCurrentMessage(){
System.out.println(msg);
}
public void updateMessage(String msg) {
this.msg = msg;
}
public static Singleton getInstance() {
if (single_instance == null) {
single_instance = new Singleton();
}
return single_instance;
}
}
Mind you that we are strictly speaking of the legality of this approach. Another discussion to be had is regarding the practicality of the approach where you need to consider many things like:
Testability of the code - one of the reasons why Singleton are not liked very much
Usability in multithreaded applications - Many safeguards are needed when objects mutate in multithreaded context.
There could be many others; albeit some of those (if not all) apply to non-Singleton objects as well.
A friend of mine showed me this as his implementation of the singleton pattern. It seems to work fine, from what I've tested so far. I cannot tell why, but referencing "this" as seen below, just seems like bad practice to me.
Is this usage of "this" in the constructor legitimate?
public class Singleton {
private static Singleton unique = null;
private Singleton() { unique = this; }
public static Singleton instance() {
if (unique == null)
new Singleton();
return unique;
}
}
Is there even a significant difference, compared to doing it the usual way:
public class Singleton {
private static Singleton unique = null;
private Singleton() { }
public static Singleton instance() {
if (unique == null)
unique = new Singleton();
return unique;
}
}
I have not been able to find any reasonable answers to my questions.
So, thanks in advance!
Is this usage of "this" in the constructor legitimate?
It would work, but unreasonable and barely readable. It feels more like a code smell.
Is there even a significant difference, compared to doing it the usual way?
Readability and maintainability should always be considered. It'll be harder to mock and/or use this singleton cause its implementation kind of unique.
Also, as pointed out in the comments. None of the examples are thread-safe. Means this is not a true singleton.
If you want a thread-safe singleton with lazy initialization, I'd suggest to implement it as follows:
public class Singleton {
private static Singleton unique = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (unique == null) {
unique = new Singleton();
}
return unique;
}
}
You can enhance it by introducing Double check locking:
public static synchronized Singleton getInstance() {
if (unique == null) {
synchronized (Singleton.class) {
if (unique == null) {
unique = new Singleton();
}
}
}
return unique;
}
Additional Info
There are multiple ways of implementing Singleton pattern:
https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/
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.
Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)
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();
}
}