Does the singleton pattern make sense for a Socket? - java

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.

Related

Deadlock in Java Static Initialization of Singleton Classes

I am designing a game in libgdx, and i decided to make certain manager classes singletons because I noticed that I was often only using one instance of a class, and then passing the same instance to many other classes through constructors, which was very painful to do. Now, I have one manager class that initializes many other classes in it's constructor. I did this by using static block initializers for each class, like so:
public class Example{
private static Example instance;
static{
try{
synchronized(Example.class){
instance = new Example();
}
}catch(Exception e){
throw new RunTimeException("Failure to initialize Example instance");
}
public static Example getInstance(){
return instance;
}
In the main manager I create an instance of each class through the getInstance method.
The problem that arises is this: say I have static singleton classes Example1 and Example2.
In Example1's constructor I make a variable called:
example2 = Example2.getInstance();
but because example2 and example1 need to use each other's methods, in Example2's constructor I make:
example1 = Example1.getInstance();
The problem should be easy to see. Because example1 is waiting for example2 to finish initializing, and example2 needs example1's instance, it ends up creating a deadlock and crashing through the above codes RunTimeException.
this seems easy to fix using just two example classes, but the problem is confounded when I have 6 different singleton manager classes that almost all need to communicate in some way. Easiest solution would obviously not use this methodology, but that would require me to rewrite most of my code.
I can't figure out how to use this methodology of singleton classes without running into this issue, as most of the classes need information from the other classes in the constructor in order to function.
do I remove all of the code from the constructors of the singleton classes, or do something else?
It's not a deadlock, it's infinite recursion. There is no way around it, you must refactor your code.
Best thing is not to have any logic in your constructors, just initialization of member variables. Since you don't need to store the singletons as members in your classes, there really should be no need to access them in your constructors. Just use the appropriate getInstance() method to access a singleton from inside the methods of your other singletons.
I don't use many singletons any more. I consider a singleton to be a use case, rather than a "type of class", and then rely on something else to manage the "singleton-ness" of it (such as an injection framework). When I don't have one of those, I create a single "singleton" to manage the applications classes-to-be-used-as-singletons.
So, in this case, you can have this class manage the construction and interdependencies for you rather than have the classes manage them for themselves.
public class Singletons {
private Example1 example1;
private Example2 example2;
private Example3 example3;
private static Singletons instance;
static {
Example1 example1 = new Example1();
Example2 example2 = new Example2();
Example3 example3 = new Example3();
instance = new Singletons();
example1 = new Example1();
example2 = new Example2();
example3 = new Example3();
example1.setExample2(example2);
example2.setExample3(example3);
example3.setExample1(example1);
instance.setExample1(example1);
instance.setExample2(example2);
instance.setExample3(example3);
}
public Example1 getExample1() {
return example1;
}
private void setExample1(Example1 example1) {
this.example1 = example1;
}
public Example2 getExample2() {
return example2;
}
private void setExample2(Example2 example2) {
this.example2 = example2;
}
public Example3 getExample3() {
return example3;
}
private void setExample3(Example3 example3) {
this.example3 = example3;
}
public Singletons getInstance() {
return instance;
}
}

Is this the wrong way of initializing Singleton classes in Java? [duplicate]

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).

private static ClassName ClassInstanceVariableName=null;.....what is this?

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.

What is the issue with this java singleton class implementation?

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

How to synchronize static method in java

I come up with this question when implementing singleton pattern in Java. Even though the example listed below is not my real code, yet very similar to the original one.
public class ConnectionFactory{
private static ConnectionFactory instance;
public static synchronized ConnectionFactory getInstance(){
if( instance == null ){
instance = new ConnectionFactory();
}
return instance;
}
private ConnectionFactory(){
// private constructor implementation
}
}
Because I'm not quite sure about the behavior of a static synchronized method, I get some suggestion from google -- do not have (or as less as possible) multiple static synchronized methods in the same class. I guess when implementing static synchronized method, a lock belongs to Class object is used so that multiple static synchronized methods may degrade performance of the system.
Am I right? or JVM use other mechanism to implement static synchronized method? What's the best practice if I have to implement multiple static synchronized methods in a class?
Thank you all!
Kind regards!
The best approach (which makes as few changes in your code as possible) is to do like this:
public class ConnectionFactory{
private static ConnectionFactory instance = new ConnectionFactory();
public static ConnectionFactory getInstance(){
return instance;
}
private ConnectionFactory(){
}
}
As you can see, there is no real need in getInstance method now, so you can simplify the code to:
public class ConnectionFactory{
public static final ConnectionFactory INSTANCE = new ConnectionFactory();
private ConnectionFactory(){
}
}
UPD about synchronization: the best way is synchronizing on a lock which is not visible to outer classes, i.e.:
public class ConnectionFactory{
private static final Object lock = new Object();
public static void doSmth() {
synchronized (lock) {
...
}
}
public static void doSmthElse() {
synchronized (lock) {
...
}
}
}
There are many discussions about "why synchronizing on this is a bad idea" (like this one), I think that the same is actual for synchronizing on class.
There are a couple of ways you can create a singleton.
One recommended way is to use an enum (guaranteed to only create one instance):
public enum ConnectionFactory {
INSTANCE;
}
Or you can create it statically when the class loads:
public class ConnectionFactory {
private static ConnectionFactory INSTANCE = new ConnectionFactory();
private ConnectionFactory() {}
public static ConnectionFactory getInstance() {
return INSTANCE;
}
}
If you need to lazily load it you can use this idiom (rather than the double checked locking anti-pattern )
public class ConnectionFactory {
private static class ConnectionFactoryHolder {
private static ConnectionFactory INSTANCE = new ConnectionFactory();
}
public static ConnectionFactory getInstance() {
return ConnectionFactoryHolder.INSTANCE;
}
}
Yes, static methods are synchronized on their class object. I wouldn't worry about performance here, as probably this will not be your performance hot spot. Do it simple, optimize when and where you need to.
Static synchronized methods use the lock on the class. In the case of your example it would be accessing the lock on the ConnectionFactory class object. Best practice is not to hold onto locks for longer than you have to. Whether you have multiple synchronized methods is not a problem in itself.
Effective Java recommends using Enums to create singleton. So you code would look something like this:
public enum ConnectionFactory{
INSTANCE;
// Other factory methods go here.
}
}

Categories

Resources