This question already has answers here:
What is an efficient way to implement a singleton pattern in Java? [closed]
(29 answers)
Closed 6 years ago.
I had my singleton class initially like this
private static MqttHandler instance = new MqttHandler();
private MqttHandler(){};
public MqttHandler getInstance(){
return instance;
}
Now in one phone it was working as expected, but in another, seems like it was creating many instances, since whenever I tried to log something, it did log multiple times. I have no idea why.
The second time I tried using this
private MqttHandler instance;
private MqttHandler(){};
public MqttHandler getInstance(){
if(instance==null) instance == new MqttHandler();
return instance;
}
Seems to be working, at least for now, not sure if its going to crash later, Does this mean that, in my first method, whenever I returned instance, it was calling
new MqttHandler();
thus creating new instances all the time? Why would it work on one device correctly, and then refuse completely on a different one?
This is how to implement a simple singleton:
// It must be static and final to prevent later modification
private static final MqttHandler INSTANCE = new MqttHandler();
// The constructor must be private to prevent external instantiation
private MqttHandler(){};
// The public static method allowing to get the instance
public static MqttHandler getInstance() {
return INSTANCE;
}
Your second approach will work only on single threaded application because if you call getInstance at the same time with several concurrent threads, it will create several instances of your object such that the contract of your singleton would be broken. So if you need to properly lazy create your singleton, here is how to proceed:
// The constructor must be private to prevent external instantiation
private MqttHandler(){};
// The public static method allowing to get the instance
public static MqttHandler getInstance() {
return MqttHandlerHolder.INSTANCE;
}
/**
* The static inner class responsible for creating your instance only on demand,
* because the static fields of a class are only initialized when the class
* is explicitly called, this rule is also applicable to inner static class
* So here INSTANCE will be created only when MqttHandlerHolder.INSTANCE will be called
*/
private static class MqttHandlerHolder {
private static final MqttHandler INSTANCE = new MqttHandler();
}
Both should have the same effect. Of course the latter has the benefit that the object isn't created until actually needed, but be aware that the object could be created multiple times due to concurrent calls to getInstance.
Also, you need a "static" declaration in getInstance (otherwise you would have to create an instance to get the singleton).
Related
This question already has answers here:
When would the garbage collector erase an instance of an object that uses Singleton pattern?
(4 answers)
Closed 6 years ago.
Sorry if title is confusing, I will explain. I have a class using a Singleton pattern, and has a time-stamp value which is set at instantiation. In the example below, a second class instantiates this Singleton (and the default value). I then set the reference of that second class to null. I then retrieve the Singleton again and it still has the same default value. This is the desirable functionality for my needs, but I want to better understand why the Singleton stayed alive. Something to do with the JVM? Or would be there some sort of garbage collection which would delete the Singleton instance (and its original default value)?
MySingleton.java
import java.sql.Timestamp;
public class MySingleton {
private MySingleton() { }
private static MySingleton instance;
private static String defaultTimeStamp;
public static MySingleton getInstance() {
// Lazy instantation
if (instance == null) {
instance = new MySingleton();
// Assign the default value
java.util.Date date = new java.util.Date();
defaultTimeStamp = (new Timestamp(date.getTime())).toString();
}
System.out.println(defaultTimeStamp);
return instance;
}
}
SingletonTest.java
public class SingletonTest {
public static void main(String args[]) throws InterruptedException {
MySingleton mySingleton1 = MySingleton.getInstance();
mySingleton1 = null;
Thread.sleep(1000);
MySingleton mySingleton2 = MySingleton.getInstance();
}
}
Output
2016-04-18 11:30:47.151
2016-04-18 11:30:47.151
The reference from the static field prevents the singleton from getting garbage collected. The singleton object is referenced from a static field in the MySingleton class. The class is referenced from the classloader. Once a class is loaded it doesn't get GC-ed until its classloader goes away.
Nulling out the variable that contains the reference returned from the call to getInstance has no effect on the reference contained in the static field instance.
Part of the problem with using static fields is the potential for memory leakage, that things referenced from them can hang around taking up memory for an indefinite time.
I want to store an object state between activities (already considered Parcelables, JSON, yadda yadda) but since I have a couple of Singletons, might as well refer to them in a class that extend Application (modularity + easy to maintain).
So to my question, let's say I have a simple singleton:
class SimpleSingleton
{
private static final SimpleSingleton instance; //The question will refer this line later.
public static SimpleSingleton getInstance()
{
return instance;
}
private SimpleSingleton(){}
}
1: At first I create an initInstance() method within the above class, e.g:
class SimpleSingleton
{
//... the code above
public static void initInstance()
{
if(instance == null) instance = new SimpleSingleton();
}
}
2: Hence the below works, (in which afterwards, I can refer to the singleton from any activity via CustomSingleton.getInstance()):
class MyApp extends Application
{
#Override
public void onCreate()
{
super.onCreate();
initSingletons();
}
protected void initSingletons()
{
SimpleSingleton.initInstance();
}
}
BUT. What if I declare
private static final SimpleSingleton instance = new SimpleSingleton();
instead of
private static final SimpleSingleton instance;
in the SimpleSingleton class?
I assume the object is initialized during compile time, so doesn't that makes the whole #1 and #2 unnecessary? Or do I get the order wrong (especially WHEN the class is actually initialized)? I came from C# and currently developing for Android so this kinda gave me a quick gotcha when I want to refer to my Singletons. Also, I ask this since according to this blog:
The explanation of the weird behavior I saw that makes more sense to me is that the static variables instances are bound to the class loader of the class that first initialized them.
The only difference i can think of is when you do
private static final CustomObject instance = new CustomObject();
when you application is launched it will create and allocate space for it.
Note it might never be used but it would still be using memory.
when you create it on an onCreate method it will only create an instance when it is called.
Using static also has one more disadvantage that is it will use your perm gen space and if by chance it fails to give it space or fails to create it your program will crash on startup. Leaving you confused.
I strongly suggest using the onCreate method approach.
I have a Java application in which I have a socket. Now it's very important that only one socket is open at any point. I figure that a good way to ensure this is to create a wrapper class that enforces the singleton property on a Socket instance. For clarification: by singleton pattern I am referring to the following generic class design:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
//Private constructor prevents instantiating and subclassing
private Singleton(){ }
//Static 'instance' method
public static Singleton getInstance( ) {
return INSTANCE;
}
//...Other class methods
}
I am wondering if the idea of a singleton socket makes sense conceptually. The Socket will need to be able to reconnect and disconnect at any point throughout the course of the program and I'm not sure if that is possible with a singleton.
As far as I can tell this is not possible although I am hoping that there is some trick to it or I am simply misunderstanding something.
Absolutely, why not? Singleton pattern applies when you need a unique instance of a class accesible in any point of the application.
In this case, your singleton wrapper could create an instance of the socket in the constructor and expose methods to manage the socket transparently for the rest of the application.
A pseudocode example could be:
public class SocketDevice{
private static final SocketDevice INSTANCE = new SocketDevice();
private Socket socket;
//Private constructor prevents instantiating and subclassing
private SocketDevice(){
// instanciates the socket ...
}
//Static 'instance' method
public static SocketDevice getInstance( ) {
return INSTANCE;
}
public void open(){
// ...
socket.open()
// ...
}
public void close(){
// ...
socket.close()
// ...
}
// ...
}
I don't see that this really buys you anything: indeed it may just give you a false sense of security. It doesn't stop any other part of the application from calling new Socket(...). I would just go with a Socket as an instance member somewhere.
Well there is a static implementation here, I don't understand.I have previously used static but not extensively, can anyone help me to understand the code. Here is the code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_Class {
String driver_ClassName="com.mysql.jdbc.Driver";
String URL_connection="jdbc:mysql://localhost:3306/vendor";
String user="root";
String password="lifesuckzz";
//can anybody explain what the following line means, especially the static part.......
private static Connection_Class connectionclass=null;
private Connection_Class(){
try{
Class.forName(driver_ClassName);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException{
Connection con=null;
con=DriverManager.getConnection(URL_connection,user,password);
return con;
}
public static Connection_Class getInstance(){
if(connectionclass==null){
//I know its returning an instance here
connectionclass=new Connection_Class();
}
return connectionclass;
}
}
static means that the variable is a member of the class itself (only one copy) rather than a member of objects of the class (one per object). You can access a static variable without having an object. In this case you can call Connection_Class.getInstance() to get the single Connection_Class object shared by the whole program.
It's a design pattern called Singleton Design Pattern.
This is useful when exactly one object is needed to coordinate actions across the system
http://en.wikipedia.org/wiki/Singleton_pattern
Answer to your question :
Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static getInstance() method.
This is an example of a Singleton design pattern. By marking the constructor private you ensure that you *control instantiation to have one and only one instance per JVM*.
public final class Singleton {
private static Singleton INSTANCE = new Singleton();
private Singleton () {
if (INSTANCE != null)
throw new IllegalStateException("Already instantiated.");
}
// getInstance() method here (refer below)
}
The keyword static ensures that the Singleton becomes accessible as a member of the class (like Singleton.getInstance()) without requiring a constructor call which isn't possible now since it has been marked private.
Also, your Singleton implementation is not thread-safe. Synchronize your getInstance() method.
public static synchronized Connection_Class getInstance(){
if(connectionclass == null){
connectionclass = new Connection_Class();
}
return connectionclass;
}
This avoids any race condition between multiple threads requesting this connection object.
This is an example of the singleton pattern. It creates one reference of the connection class within your app (strictly speaking, within your classloader).
Singleton is a fairly common pattern in many OO langauges, but is often seen as an anti-pattern since it makes testing difficult.
I have come across another article in stackexchange on various ways to implement java singleton. One of the ways shown is the following example. It has been voted very low. Wanted to understand why.
What is an efficient way to implement a singleton pattern in Java?
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
// do some of your instantiation stuff here
}
private Singleton() {
if(instance!=null) {
throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
}
}
public static getSingleton() {
return instance;
}
}
As #Craig says in the comments:
Not true. static variables are initialized along with static blocks when the class is loaded. No need to split the declaration.
Essentially it was down voted because it was misinformation, a lot of what he was saying was just plain not true. Specifically, initializing a static variable with a static method will occur when the class is loaded, while the author claimed that this was not the case.
His argument also doesn't really make sense, "data insertion" could just be done within the constructor.
With that said, the above code will work fine, it's just an odd way of doing it, and arguably the least stylistic.
following solution make sure it's thread safe
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
This is not a good way to implement it.
As static variables are initialized at JVM load time, just make the singleton final:
public final class Singleton
{
private static final Singleton INSTANCE = new Singleton();
private Singleton()
{
// build it
}
public static Singleton getInstance()
{
return INSTANCE;
}
}