I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerFactorySingleton {
private static EntityManagerFactorySingleton singleton;
private EntityManagerFactory emf;
public EntityManagerFactorySingleton(){
emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}
public synchronized static EntityManagerFactorySingleton getInstance() {
if(singleton == null) {
singleton = new EntityManagerFactorySingleton();
}
return singleton;
}
public EntityManagerFactory getEntityManagerFactory(){
return emf;
}
}
Your code is not "solid":
constructor must be private for a singleton
you shouldn't have the getInstance() method synchronised, although you need to perform the initialisation thread-safe. That's because after initialization, all the threads that need the instance will have to wait for each other (and that's a useless bottleneck).
Only if your instance is null, call a synchronized (private) method that performs the initialisation; inside that method, check again if the instance is null. Another approach is to have a private inner class SingletonHolder that holds the instance, so you'll rely on the class-loader for performing the thread-safe initialisation.
However, if you can't (don't want to) avoid using a singleton, a very good choice would be an enum with only one constant defined: INSTANCE;
public enum EntityManagerFactorySingleton {
INSTANCE;
// all your code -- fields, constructor, instance / static methods get in here
// you can still have the `getInstance()` static method returning INSTANCE, if you want.
}
The only drawback is that you cannot perform lazy initialisation for the INSTANCE, but you're now thread-safe and ready for serialization or cloning issues without any effort.
To answer your question - I think you should make the constructor private, to ensure other Classes cannot instantiate another EntityManagerFactorySingleton. However, if that is not happening, then I can see no reason why this class would be causing a pooling issue.
The code is not thread safe. (Sorry, missed the synchronized)
You should not use singletons.
Instead, use a DI framework like Spring, guice or maybe your deployment envionment already offers one.
This will make your code much more robust and much more simple to test.
Related
Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg
I have the following code:
public class EntityManagerFactoryProviderImpl implements EntityManagerFactoryProvider {
private EntityManagerFactory entityManagerFactory=null;//line XXX
public EntityManagerFactory getFactory(){
if (entityManagerFactory==null){
buildFactory();
}
return entityManagerFactory;
}
private synchronized void buildFactory(){
if (entityManagerFactory!=null){
return;
}
entityManagerFactory=...
}
}
So I need that entityManagerFactory instance was created only once - when getFactory() is first called.
Must I set variable entityManagerFactory on line XXX as volatile this case?
Also, EntityManagerFactoryProviderImpl is an OSGI Singleton Declarative Service, so there is always only one instance of this class.
There are theoretical possibilities that multiple threads are calling the code in parallel; and due to not using volatile, thread A doesn't see updates that thread B made.I have never encountered such behavior myself, but surr: it is possible and when it happens, very strange bugs might come out of having two instances of the same singleton.
You can study this SEI cert site for a full discussion of the subject.
I cannot see why you need to make this volatile. You use the double checked locking solution in your example. The link in the accepted answer also indicates this is compliant.
So the accepted answer is actually wrong, you do not need volatile. Howeer, the cleanest solution for this kind of initialization is the "initialize-on-Demand Holder Class Idiom" which is also at the link.
Update I was wrong. The double check locking can fail because the EntityManagerFactory object can be seen in a partially constructed state, only final fields in this objects are guaranteed to be seen. This is explicitly mentioned in http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5-110
int j = f.y; // could see 0
The "initialize-on-Demand Holder Class Idiom" is fastest.
The code in question isn't threadsafe because it has a check then act problem in the public method. The reason for this problem is that shared mutable state isn't properly syncrhonized in the class. Here's a solution:
public class EntityManagerFactory implements ....{
private static class EntityManagerHolder {
public static EntityManager entityManager = new EntityManager();
}
public static EntityManager getEntityManager(){
return EntityManagerHolder.entityManager;
}
}
Notice that there's no synchronized keyword here. This is because entityManager is initialized as static in the holder class which means it's loaded after class loading but before any threads can start and hence no synchrnonization is needed.
The sole purpose of the holder class is to prevent an eager initialization cost by using the JVM lazy class loading strategy. The holder class is only initialized when it's actually needed rather than at class load time with an eager static initialization.
Bottomline: You avoid synchronized and eager initialization and get a singleton all in one fell swoop. ;)
Suppose I want to implement the class which will provide me Connection for database connectivity. I can implement the same thing with two different code snaps given below.
Method 1:
class DBConnection1 {
private static DBConnection1 instance = new DBConnection1();
private DBConnection1(){
}
public static DBConnection1 getInstance(){
return instance;
}
public Connection getConnection(){
Connection connection = null;
//do my stuff to init the connection
return connection;
}
}
Method 2:
class DBConnection2 {
public static Connection getConnection(){
Connection connection = null;
//do my stuff to init the connection
return connection;
}
}
And Accessing the above methods like,
class TestConnection{
public static void main(String[] args) {
//using method 1
Connection connection1 = DBConnection1.getInstance().getConnection();
//using method 1
Connection connection2 = DBConnection2.getConnection();
}
}
I have little doubt which is better and why? And what is difference over there?
At a very high level you might get confused and it looks that they both are doing the same task. But there is a lot of difference. I'm answering this question in general. You can understand the advantages based on your application(type).
Singleton stores common data in only one place. It will greatly simplify the architecture of a program and helps you to reuse code. Singletons allow you control object state much easier. This improves code-sharing, and quality of code. Hence it becomes easier to maintain. Singleton allows you to override in case you want to override it. Lazy loading can be done using Singleton Classes. Singleton is more object oriented. Static objects are stored in stack but singleton objects are stored in heap.
Static classes are difficult to test when compared to Singleton(Singleton is very easy to mock. Eg- while using JUnit Tests). If you are using Spring or any such dependency injection framework, its better to use Singleton than static. Static Class cannot be passed to a method or inherited. Static classes can create issues in a concurrent environment due to shared data. its better not to maintatin state inside static class. You can refer more about Singleton here http://en.wikipedia.org/wiki/Singleton_pattern or http://www.tutorialspoint.com/java/java_using_singleton.htm .
The only advantage that i see with static class is that its faster. Use static only when a set of functions have to be kept together.
Depends on what you try to achieve. For example, if you are sure that you'll need this connection through all your app lifecycle - static method is for you. But if you are not sure about that - use singleton. But in real projects you should probably not use static methods for anything but some kind of utils methods, because singleton is much more flexible comparing to a static methods.
But there are minimum one more pattern that you'll probably be interested in. Dependency injection. It could be a little bit more complex than a singleton, but again it's much more flexible. The main point of if that in a big project you may need some functionality providing by database and you'll use one class to access it. But later data separated by two databases and two classes with the same interface and instead if rewriting the code of classes that use a database, you changed implementation that would be injected in a particular class. There are much more benefits of using dependency injection that I described, but I hope you'll got the point.
The two alternatives are equivalent. However, I would prefer the singleton one, because it is easier to swap the implementation or override behavior with subclassing in the future.
Another point that will make much more difference is whether to create a new connection for every use or reuse connection objects. This will make a lot of difference concerning prepared statements and commits / rollbacks.
You are mixing up two different patterns, namely Static Factory Method (not the same as the GoF Factory Method) and Singleton.
Static Factory Method is concerned with creating instances. The Singleton pattern is used to ensure, that there is only one object of the Singleton class.
E.g. a typical static factory method:
public DBConnection {
private DBConnection(String param) {
//...
}
public static DBConnection createConnection(String param) {
return new DBConnection(param);
}
}
Note, that typically a factory method is called create... or getNewInstance or something similar to emphasize, that this method will always return a new instance.
The same as a Singleton:
public DBConnection {
private static DBConnection instance;
private DBConnection(String param) {
//...
}
public static DBConnection getInstance() {
if(instance == null){
instance = new DBConnection("fixed param!");
}
return instance;
}
}
Note how the same instance is always returned after it was created lazily.
Nevertheless those pattern can coexist - e.g. a singleton can use a static factory method to create the instance:
public DBConnection {
private static DBConnection instance;
private DBConnection(String param) {
//...
}
public static DBConnection createInstance(String param) {
return new DBConnection(param);
}
public static DBConnection getInstance() {
if(instance == null){
instance = DBConnection.createInstance("param");
}
return instance;
}
}
I intentionally left the static factory method public, to emphasize the difference between getInstance and createInstance here.
Also private constructors play an important role in those patterns it enforces that the createInstance / getInstance methods must be used to get hold of an instance.
The short answer is that you should not use the Singleton approach. This is because you seem to be returning a new connection everytime the getConnection method is called. If this is what you really want, there is no point using a Singleton class. You should go with method 2 instead.
The long answer is that you seem to be confused about what a Singleton really is. The purpose of a Singleton class is to ensure that there is only one object of a given class created for a given ClassLoader, thus ensuring that the state of such an object is global. If your class does not contain any state, you might as well use a class that contains only static methods. Alternately, if you are using an IoC container such as Spring or Guice, you can have a Singleton enforced via the framework rather than explicitly design your class as a Singleton. A class that is explicitly designed to be a Singleton but does not have any state really doesn't make much sense.
If you plan to have a connection factory, better to to implement method1.
Because you could change you code inside of you Factory with few impact in the rest of the App.
Caution if reusing the connection, since you can share context, and that can be something you don't want!
Better is to live the ConnectionFactory get from connection's pool, one connection, then using it, then releasing it.... etc.
See factory pattern : if this is a connection factory that serves connections, better to see Factory Method Pattern
I sometimes see that people create self instance for example:
public class Example extends Service
{
private static Example mInstance = null;
public void onStart( Intent aIntent, int aStartId )
{
mInstance = this;
.
.
.
}
}
What is the purpose of this?
This is called the Singleton design pattern. Singletons are used when there is going to be a single instance of an object performing operations on non-static data.
See here.
In addition to what other answers put about Singleton pattern, self instances may be used as constants. That's the case of the Color class, that defines an instance for each of the common colours.
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
An Android Service (sub)class cannot be a singleton since the framework requires access to a default constructor for the class. The only reason I can think of for keeping a static reference to the (last) instance for which onStart was called is to simplify some internal code that may happen to reside in static methods.
Considering that onStart was deprecated a long time ago (as of API level 5), this is most likely an example of bad coding style from early days of Android.
So that other classes can get an instance and call instance methods on the object. Its frequently used with the Singleton pattern. And for Services and Activities in Android it's a very bad idea- it keeps a reference to the Activity/Service around after it ends, which will cause a memory leak.
In a thread-unsafe singleton pattern implementation, you would have a private constructor, and a public static getInstance method initializing that instance if necessary and returning it.
Here's an example. Note that it is advised to leverage the commodity of a single-element enum instead of the code below, to achieve a "true" singleton.
public class MyThreadUnsafeSingleton {
private static MyThreadUnsafeSingleton instance;
private MyThreadUnsafeSingleton() {
//TODO some ctor logic
}
public static MyThreadUnsafeSingleton getInstance() {
if (instance == null) {
instance = new MyThreadUnsafeSingleton();
}
return instance;
}
}
Final note, there is a variation of the above pattern that is thread-safe across a single classloader through the usage of a nested "holder" class, but that's quite out of scope.
If it has a private default constructor, it's probably a singleton.
If it doesn't, it's something weird.
This sort of layout forces all object instances of this class to share data, regardless of when they are instantiated. The object instance on which OnStart is called will become the underlying data source for any references to this class, regardless of when they were declared or instantiated (before or after OnStart), and regardless of what thread they were created on.
Of course it is always possible there are members of the class that don't bother with mInstance.Member and use this.Member instead. That sort of mixing and matching would probably end up being disastrous.
It's hard to imagine the specific use for this but my guess is that the class is an abstraction of some stateful resource that is global with respect to the process, e.g. a form/window or a web service client that caches its credentials. Could be anything though.
If this code was written around 2003-2005 (early c# days) I'd guess that it is a sloppy implementation of a Singleton-- it was sort of in vogue back then as design patterns were becoming a thing and Singleton was the example in all the textbooks. Turns out it's a horrible pattern for dependency injection and mocking, so these days this pattern doesn't get used as much.
This paradigm is often used for objects that are heavy or slow to construct and only one is needed.
public class Server {
private static Server server = null;
// Stop them making their own.
private Server () {
// Heavyweight stuff.
}
public static Server getServer () {
if ( server == null ) {
// Heavy constructor.
server = new Server();
}
return server;
}
}
In a multi-thread environment it is usually combined with the singleton design pattern.
This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73