Java Simple Way to Create Application Singleton - java

I am trying to create a global connection pool for my Java app.
My problem is that when I use the following approach:
package mypackage;
public class Singleton
{
private static MyPool connPool;
private Singleton() {}
public MyPool getPool() {
if (connPool == null)
connPool = new MyPool();
return connPool;
}
}
Now if I have two classes A and B which import Singleton class above using
import mypackage.Singleton;
Then I will end up invoking new MyPool() twice, which means I will open double the connections to my resource (such as database). How can I ensure that I only create the pool one time in my application?
I found some complicated ways of accomplishing this on the internet using reflection. Is there an easier (and/or better) way?

I think you are looking for a thread-safe implementation of a Singleton class here. Of course, the way to achieve this is using enums, but for your case, you can implement double-check locking to ensure no two threads can call new MyPool() simultaneously.
Also, I think in your code, you are actually implementing a factory class, not really a singleton. Your MyPool is a different class than Singleton, which could have a public constructor.
I have made the appropriate changes with comments.
Double check-locking basically just checks the thread-safety before and after null-check, because the whole method is not synchronized, so two threads can indeed get the null value in the condition even after synchronization block, hence the second synchronization.
Also, I think your getPool() should be static. You won't be able to call getPool() without an explicit object of Singleton, which I think you don't need.
Corrected version:
package mypackage;
public class Singleton{
// Instance should be of type Singleton, not MyPool
private static Singleton connPool;
private Singleton() {}
// *static* factory method
public static Singleton getPool() {
// Double-check-locking start
synchronized(Singleton.class){
if (connPool == null){
// Double-check-locking end
synchronized(Singleton.class){
//create Singleton instance, not MyPool
connPool = new Singleton();
}
}
}
return connPool;
}
}

Related

Lazy Singleton what advantages over thread safe one

We had design patterns in school and learned the implementation of a singleton (lazy / not thread safe one) like this:
package com.crunchify.tutorials;
public class CrunchifySingleton {
private static CrunchifySingleton instance = null;
protected CrunchifySingleton() {
}
// Lazy Initialization (If required then only)
public static CrunchifySingleton getInstance() {
if (instance == null) {
// Thread Safe. Might be costly operation in some case
synchronized (CrunchifySingleton.class) {
if (instance == null) {
instance = new CrunchifySingleton();
}
}
}
return instance;
}
}
Now I found the implementation like this:
package com.crunchify.tutorials;
public class ThreadSafeSingleton {
private static final Object instance = new Object();
private ThreadSafeSingleton() {
}
// Runtime initialization
// By defualt ThreadSafe
public static Object getInstance() {
return instance;
}
}
Now I am wondering when the first implementation makes more sense to use, because according to http://crunchify.com/thread-safe-and-a-fast-singleton-implementation-in-java/ the second one is thread safe and needs less lines.
Difference is in the time singleton object is instantiated. Second snippet instantiates singleton object only once at class instantiation time. It is useful if no additional data required for this process. Note that if instantiation error occured (does not matter in that simple case: just Object) singleton class would not be available at all.
First snippet instantiates singleton object when it is being requested. You may modify that class to provide some mechanism to store any initialization data and/or catch instantiation errors.
how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created.

Two ways of Singleton design [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'm trying to learn about the Singleton design pattern and I found two different ways of only creating 1 instance.
public class Singleton {
private static Singleton instance; // attributes omitted
private Singleton() {
// omissions
}
public static Singleton instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// other methods omitted
}
public class Singleton {
private static int bound = 1;
public Singleton() {
if (bound == 0) {
throw new RuntimeException(
"Singleton: No more objects must be created");
}
bound--;
}
}
Which is preferred to use and why? Are they equally as good?
Not sure about the Java way to do it but in my opinion I would just use the first way. I consider that it would be bad to throw and exception in your constructor and to expose publicly
Since you only want to get your unique instance the constructor should be private.
The first of your methods is a common way to try to implement a lazily-created singleton. It has some issues such as lack of thread safety, although they can be overcome via mechanisms like synchronization.
The second of your methods is truly vile. Exceptions should only be used to indicate exceptional conditions in the code. If you don't want somebody to create an instance of the class, don't let them - you can take control of the instantiation. Forcing them to catch an exception is a totally unnecessary burden on users of your class. (And it's not thread safe either).
A single-element enum is the best and easiest way to create a singleton.
However, there are certain circumstances in which you can't use an enum, for instance if your class needs to extend another class:
If you can initialize the instance eagerly, just do that:
class Singleton /* extends Blah */ {
private static final Singleton INSTANCE = new Singleton();
static Singleton getInstance() { return INSTANCE; }
}
If you want to defer initialization until it is required, you can use the lazy holder idiom:
class Singleton /* extends Blah */ {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
static Singleton getInstance() {
return Holder.INSTANCE;
}
}
The Holder class is not initialized until getInstance() is called, so the Singleton instance is not created until then.
It should be noted that singletons are considered by some to be a design antipattern.
Don't use either. As of Java 5, the preferred technique is to use an enum with a single value, usually named INSTANCE.

Two way of implementing singleton with thread safe lazy initialization

Static method and variable:
public class Singleton{
private static Singleton singleton = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(singletion == null)
singleton = new Singletion();
return singleton;
}
}
Second after Java 1.5
public class Singleton{
private static volatile Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
synchronized(this){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
So what's the pros and cons for these two thread safe code and when should we use which?
The second is thread safe but the following is much simpler, and faster as it doesn't require a synchronized block.
public enum Singleton {
INSTANCE;
// define fields and methods here.
}
to access
Singleton.INSTANCE.method();
Note: an enum can implement an interface if you need.
Both implementations are thread-safe and valid.
The former is shorter. It is more readable and maintainable.
The latter is faster, and it's also faster than most people think. Depending on the implementation of the Java VM, reading a volatile variable is as fast as reading a non-volatile variable on x86. That means the overhead occurs only during the initialaztion. But as soon as the singleton has been initialized, there is no overhead at all.
If performance is really an issue, you should use the latter. Otherwise use the former, because the need for readability and maintainability is often underestimated.
The safest way to go about doing a thread-safe singleton is via the initialisation on demand holder idiom:
public class Foo {
private Foo() {}
private static class Holder {
private static final Foo INSTANCE = new Foo();
}
public static Foo getInstance() {
return Holder.INSTANCE;
}
}
This works in Java versions that didn't properly support the volatile keyword. The neat thing about this pattern is that it uses implicit locking only on the first access of getInstance. After that, access is unsynchronized. This is due to a fun little quirk of memory management and static loading in Java.
Both examples are of lazy initialization of singleton i.e. you initialize the singleton at the moment you need.The second example is an example of double checked locking which is primarily aimed at thread-safe.
The second one 'double checked' singleton is faster because it don't need to acquire lock whenever you ask for instance (despite first calls). Anyway best way to control life cycles of your objects is using dependency injection.
The first one is not thread safe. It would be thread safe if getInstance was synchronized.
If you need thread safety, use the second one.
There is a much simpler third way though, which is slightly different (the Singleton gets created at a different time):
public class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
}

How to use a factory pattern to get the instance of my Database Client?

Below is my Interface -
public interface IDBClient {
public String read(String input);
public String write(String input);
}
This is my Implementation of the Interface -
public class DatabaseClient implements IDBClient {
#Override
public String read(String input) {
}
#Override
public String write(String input) {
}
}
Now I am thinking to write Thread Safe Singleton Factory to get the instance of DatabaseClient so that I can call read and write method accordingly.. So I wrote like this by following the Initialization On Demand Holder idiom, it is still incomplete -
public class DatabaseClientFactory {
public static DatabaseClientFactory getInstance() {
return ClientHolder.s_instance;
}
private static class ClientHolder {
}
}
And I am not sure how to get the instance of DatabaseClient correctly in my above Factory? Do I need to add another method getClient() to get the instance of DatabaseClient and then call like this -
IDBClient client = DatabaseClientFactory.getInstance().getClient();
client.read(input); // or client.write(input)
You shold use Initialization-on-demand holder idiom, implementing your factory:
public class DatabaseClientFactory {
private DatabaseClientFactory() {}
private static class LazyHolder {
private static final DatabaseClient INSTANCE = new DatabaseClient();
}
public static DatabaseClient getInstance() {
return LazyHolder.INSTANCE;
}
}
This code doesn't need synchronization because of the contract of the class loader:
the class loader loads classes when they are first accessed
all static initialization is executed before anyone can use class
class loader has its own synchronization that make previous two points guaranteed to be thread safe
Here is very a nice description of correct implementation of singleton from Joshua Bloch's (one of the Java's creators) "Effective Java" book. I would strictly recommend to read at least this chapter.
A few comments:
If you want your DatabaseClient to be singleton, you have to move your factory method to this class and make it's constructor private. Otherwise there is no guarantee, that everyone will use your factory and someone won't create the second instance of this class;
Even with such approach there is no guarantee, that someone won't use reflection to create new instance of your "singleton";
If you decide for some reason to make your DatabaseClient serializable - you'll expose another ability of getting the second instance of "singleton" and will have to apply some additional techniques to avoid this (which are also not always effective).
If you still decide to go this way - you can use one of the approaches suggested by "AgilePro" or "user987339" (with moving that logic to the DatabaseClient). I believe method, described by "user987339" is preferable as it will help to make this initialization really lazy. It's not really the case with approach described by "AgilePro" cause each call to some of the static methods of that class will initialize all static fields.
If you want to get really robust singleton - I suggest you to use enums. So your DatabaseClient will look like:
public enum DatabaseClient {
INSTANCE;
DatabaseClient() {
}
public String read(String input) {
}
public String write(String input) {
}
}
And its usage:
final DatabaseClient databaseClient = DatabaseClient.INSTANCE;
P.S. One more note related to all approaches: if you get some exception during initialization of DatabaseClient - you'll get "java.lang.ExceptionInInitializerError" which won't let you to initialize this class any longer (for all further calls to this class you'll get "java.lang.NoClassDefFoundError").
This is all you need:
public class DatabaseClientFactory {
private static final DatabaseClient mySingleton = new DatabaseClient();
public static IDBClient getInstance() {
return mySingleton;
}
}
Note the private static final member that holds the singleton instance. Declaring it final prevents you fromwriting code that might create another instance. In this case we construct as static initialization time which happens before any thread can possibly access it, but you could construct with lazy initialization at run time if you desired. In this latter case you would need to make the method synchronized, which is a bit more overhead.
I made the factory method return the interface, but it could if you wish be declared to return the concrete class instead. If your concrete class has some additional methods beyond the interface you may want to do the latter.
Access it like this
IDBClient client = DatabaseClientFactory.getInstance();
It is thread safe because the variable that holds the singleton object is initialized at static initialization time, before any thread can access it. Since it is never changed after that, there is no possibility of a race condition.
This approach is simpler than that other answer because this involves only two classes, which is all you need: the factory class and the client class. One of the other answers requires three classes. This is a very small difference, since an extra class is a very small overhead, but if you believe that code should remain as simple as possible for maintenance reasons, then using three classes when two would do is a waste.

Singleton or static class?

I have the following class :
public class EnteredValues {
private HashMap<String, String> mEnteredValues;
public boolean change = false;
public boolean submit = false;
private static final EnteredValues instance = new EnteredValues();
// Singleton
private EnteredValues() {
mEnteredValues = new HashMap<String, String>();
}
public static EnteredValues getInstance() {
return instance;
}
public void addValue(String id, String value) {
if (mEnteredValues.put(id, value) != null) {
// A change has happened
change = true;
}
}
public String getValueForIdentifier(String identifier) {
return mEnteredValues.get(identifier);
}
public HashMap<String, String> getEnteredValues() {
return mEnteredValues;
}
public void clean() {
mEnteredValues.clear();
change = false;
submit = false;
}
}
This class is used to manage the values that a user has already entered, and the class should be accessible to all classes across the application.
When the activity changes I 'reset' the singleton by calling the clear method.
I chose the singleton pattern without really considering the option of a static class.
But now I was wondering if I shouldn't just use a static class..
What is the common way to handle a class that just manages values?
Is a static class faster as a singleton?
thx
The very fact that you are providing a clear method to reset the state of your Singleton dictates that you should not use Singleton. This is risky behavior as the state is global. This also means that unit testing is going to be a big pain.
One more thing. Never ever declare instance variables as public. Declare them as private or protected and provide getters and setters. Also, there is no need to initialize instance variables with a value that is their default value.
The main difference between a static class and the singleton pattern is that singleton may be used if you need to implement an interface or such. For this particular case I think you might be better off with a static class since you are not implementing any interface. Relating your question if its one faster to the other, I'd say is negligible the difference but using a static class will remove a small overhead of dynamic instantiation of the class.
What is bad in using singleton if you need such a design? If you need exactly one instance of some object designed to do specified things singleton is not a bad choice for sure.
#see Are Java static calls more or less expensive than non-static calls?
Read
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
From there:
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Just for style
I prefer not to rely on Singleton if I don't need to. Why? Less cohesion. If it's a property you can set from outside, then you can test your Activity (or whatever) with unit testing. You can change your mind to use diferent instances if you like, and so on.
My humble advise is to have a property in each of your Activities (maybe you can define a common base class?), and set it at activity initialization with a new fresh instance.
Your code will not know nothing about how to get it (except the init code and maybe you can change it in the future).
But as I've said... just a matter of taste! :)

Categories

Resources