Findbug told me that I use incorrect lazy initialization.
public static Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object();
return instance;
}
I don't see anything wrong here. Is it wrong behaviour of findbug, or I missed something?
Findbug is referencing a potential threading issue. In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.
There is a lot of reading here, but it will help explain.
The race condition here is on the if check. On the first call, a thread will get into the if check, and will create the instance and assign it to 'instance'. But there is potential for another thread to become active between the if check and the instance creation/assignment. This thread could also pass the if check because the assignment hasn't happened yet. Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.
Your code is slightly more complex than needed which might be why it's confused.
Edit: It's definitely the threading issue as the others posted but thought I'd post the double lock check implementation here for reference below:
private static final Object lock = new Object();
private static volatile Object instance; // must be declared volatile
public static Object getInstance() {
if (instance == null) { // avoid sync penalty if we can
synchronized (lock) { // declare a private static Object to use for mutex
if (instance == null) { // have to do this inside the sync
instance = new Object();
}
}
}
return instance;
}
NOTE: JohnKlehm's double lock checking solution is better. Leaving this answer here for historical reasons.
It should actually be
public synchronized static Object getInstance() {
if (instance == null) {
instance = new Object();
}
return instance;
}
You need to put a lock around instantiation to make this correct
LI: Incorrect lazy initialization of static field
(LI_LAZY_INIT_STATIC)
This method contains an unsynchronized lazy initialization of a
non-volatile static field. Because the compiler or processor may
reorder instructions, threads are not guaranteed to see a completely
initialized object, if the method can be called by multiple threads.
You can make the field volatile to correct the problem. For more
information, see the Java Memory Model web site.
You missed multi threading issue,
private static Object instance;
public static synchronized Object getInstance() {
return (instance != null ? instance : (instance = new Object()));
}
Thanks to John Klehm for posted sample
also may try to assign object instance in sychronised block directly
synchronized (MyCurrentClass.myLock=new Object())
i.e.
private static volatile Object myLock = new Object();
public static Object getInstance() {
if (instance == null) { // avoid sync penalty if we can
synchronized (MyCurrentClass.myLock**=new Object()**) { // declare a private static Object to use for mutex
if (instance == null) { // have to do this inside the sync
instance = new Object();
}
}
}
return instance;
}
your static object is not synchronized. Moreover your method is not a lazy initialization. Normally what you do is you keep a Map of object,and you initialize the desired one on demand. So you do not initialize all of them at the beginning rather than calling them when it is needed(called).
Since 1.5: the instance should be volatile and yould integrate a tmp variable to avoid using an instance that is created but its initialization is not finished yet.
private static volatile Object myLock = new Object();
private static volatile Object instance;
public static Object getInstance() {
if (instance == null) {
Object tmpObj;
synchronized (myLock) {
tmpObj = instance;
if (tmpObj == null) {
tmpObj = new Object();
}
}
instance = tmpObj;
}
return instance;
}
Related
Say Code for Singleton pattern:
class Singleton
{
private volatile static Singleton obj;
private Singleton() {}
public static Singleton getInstance()
{
if (obj == null)
{
synchronized (Singleton.class)
{
if (obj==null)
obj = new Singleton();
}
}
return obj;
}
}
obj in the above code is marked as Volatile, which means that whenever obj is used in the code, its always fetched from the main memory instead of using the cached value. So whenever if(obj==null) needs to be performed it fetches obj from main memory, though its value is set in the previous run. This is a performance overhead of using volatile keyword. How do we avoid it?
You have a serious miss-understanding what volatile does, but to be fair the internet and stackoverflow including is just polluted with wrong or incomplete answers about this. I also admit that I think I have a good grab about it, but sometimes have to re-read some things again.
What you have there shown - is called the "double check locking" idiom and it's a perfectly valid use-case to create a singleton. The question is if you really need it in your case (the other answer has shown a far more simple way, or you can read the "enum singleton pattern" too if you want). It's a bit funny how many people know that volatile is needed for this idiom, but can't really tell why it is needed.
DCL is doing two things mainly - ensures atomicity (multiple threads can't not enter the synchronized block at the same time) and ensures that once created, all threads will see that created instance, called visibility. At the same time, it ensures that the synchronized block will be entered a single time, all threads after that will not need to do that.
You could have easily done it via:
private Singleton instance;
public Singleton get() {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But now every single Thread that needs that instance has to compete for the lock and has to enter that synchronized block.
Some people think that: "hey, I can work around that!" and write (thus enter the synchronized block only once):
private Singleton instance; // no volatile
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
As simple as that is - that is broken. And this isn't easy to explain.
it is broken because there are two independent reads of instance; JMM allow for these to be re-ordered; thus it is entirely valid that if (instance == null) does not see a null; while return instance; sees and returns a null. Yes, this is counter-intuitive, but entirely valid and provable (I can write a jcstress test to prove this in 15 minutes).
the second point is a bit more tricky. Suppose your singleton has a field that you need to set.
Look at this example:
static class Singleton {
private Object some;
public Object getSome() {
return some;
}
public void setSome(Object some) {
this.some = some;
}
}
And you write code like this to provide that singleton:
private Singleton instance;
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
instance.setSome(new Object());
}
}
}
return instance;
}
Since the write to the volatile (instance = new Singleton();) happens before setting the field that you need instance.setSome(new Object());; some Thread that reads this instance might see that instance is not null, but when doing instance.getSome() will see a null. The correct way to do this would be (plus making the instance volatile):
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
Singleton copy = new Singleton();
copy.setSome(new Object());
instance = copy;
}
}
}
return instance;
}
Thus volatile here is needed for safe publication; so that the published reference is "safely" seen by all threads - all it's fields are initialized. There are some other ways to safely publish a reference, like final set in the constructor, etc.
Fact of life: reads are cheaper than writes; you should not care what volatile reads do under the hood as long as your code is correct; so don't worry about "reads from main memory" (or even better don't use this phrase without even partially understanding it).
If you want to avoid using volatile, Then you can initialize when class loading and use private constructor to avoid creating new instance.
public class Singleton{
//Initialized when class loading
private static final Singleton INSTANCE = new Singleton();
//To avoid creating new instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
You can use Lazy initialization with Holder static class
class Singleton
{
private Singleton() {}
private static class LazyLoader{
static final Singleton obj = new Singleton();
}
public static Singleton getInstance()
{
return LazyLoader.obj;
}
}
The important thing to note here is that the constructor should be fail-safe otherwise class loader will throw NoClassDefFoundError
You should use Enums for Singleton implementation.
Joshua Bloch suggests the use of Enum to implement Singleton design pattern because Java will ensures that any enum value is instantiated only once in a Java
program. The drawback is that the enum type is somewhat inflexible; for
example, it does not allow lazy initialization.
public enum EnumSingleton {
INSTANCE;
int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class EnumDemo {
public static void main(String[] args) {
EnumSingleton singleton = EnumSingleton.INSTANCE;
System.out.println(singleton.getValue());
singleton.setValue(2);
System.out.println(singleton.getValue());
}
}
This post by has nicely listed other benefits of using Enums:
java singleton instantiation
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.
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;
}
}
I have a singleton class that contains a hahsmap, the hashmap is initialised as a class variable. This map is updated correctly because when i add and print the size it changed, but, when i call it from a different thread the map is always empty. Is there a particular reason why this might happen?
I am using a ConccurentHashMap if this makes any difference.
Thanks
Singleton decleration:
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = null;
private ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static ClientRegistryDetailsSingleton getInstance() {
if(instance == null) {
instance = new ClientRegistryDetailsSingleton();
}
return instance;
}
public void setTickerToNumberRegistered(ConcurrentHashMap<String, Integer> tickerToNumberRegistered) {
this.tickerToNumberRegistered = tickerToNumberRegistered;
}
public ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}
Calling it from another thread:
String[] splitForTicker = message.split(",");
ConcurrentHashMap<String, Integer> map = ClientRegistryDetailsSingleton.getInstance().getTickerToNumberRegistered();
System.out.println("The number of items in the map from senders persepctive" + map.size());
Output:
The number of items in the map from senders persepctive 0
2012-11-12 14:29:12,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a message from the feed
The number of items in the map from senders persepctive 0
1 :the size of the map now someone has added
2012-11-12 14:29:15,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a
message from the feed
The number of items in the map from senders persepctive 0
New code for Singleton
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = new ClientRegistryDetailsSingleton();
private volatile ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static synchronized ClientRegistryDetailsSingleton getInstance() {
return instance;
}
public synchronized ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}
There is a race condition in the posted code that can result in more that one instance of the singleton being constructed if two threads call getInstance() and the singleton has not yet been constructed:
public static ClientRegistryDetailsSingleton getInstance() {
if(instance == null) { // Line 1
instance = new ClientRegistryDetailsSingleton(); // Line 2
}
}
A possible execution of two threads, T1 and T2:
T1 peforms check at line 1 and enters if branch.
T1 is suspended, with instance still being null.
T2 peforms check at line 1 and enters if branch.
T2 constructs class and assigns to instance.
T2 returns instance to caller.
T2 is suspended.
T1 is started again and constructs another instance and assigns to instance.
The construction of the single instance must be threadsafe. Possible solutions would be:
Make the getInstance() method synchronized.
Don't use lazy initialization (if possible):
private static final ClientRegistryDetailsSingleton instance =
new ClientRegistryDetailsSingleton();
Define your hash map as
private volatile ConcurrentHashMap<String, Integer>
The volatile keyword warns the JVM that the state of the variable may be changed by another thread at any time, so it must not be cached locally.
Defining the instance also as volatile might also be necessary.
Implementation of DCL antipattern: http://en.wikipedia.org/wiki/Double_checked_locking
public class ClientRegistryDetailsSingleton {
private static volatile ClientRegistryDetailsSingleton instance = null;
private final ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
private ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
// please not that constructor should be private
}
public static ClientRegistryDetailsSingleton getInstance() {
if (instance == null) {
synchronized(ClientRegistryDetailsSingleton.class){
if(instance == null)
instance = new ClientRegistryDetailsSingleton();
}
}
return instance;
}
//You should not break encapsulation and allow a link to HashMap escape
private void setTickerToNumberRegistered(ConcurrentHashMap<String, Integer> tickerToNumberRegistered) {
this.tickerToNumberRegistered = tickerToNumberRegistered;
}
//You should not break encapsulation and allow a link to HashMap escape
private ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
}
//I omitted the access to the hash map it's likely that some additional params required
public void addToClienets(String ticker){}
//I omitted the access to the hash map it's likely some additional params are required
public void removeFromClients(String ticker){}
}
I've shown this only as a synchronization example, in real life you should likely implement your singletons as Enums : What is the best approach for using an Enum as a singleton in Java?
Good morning.
I am currently working on a Java Web Service project, that is deployed on an Apache Tomcat 7 server. For the needs of the project, I need to maintain a global (among WS threads, created by every request) object in memory. Thus, I tried to implement a Singleton design pattern as follows:
public class SingletonDesign {
private static boolean _instanceFlag = false;
private static final SingletonDesign _instance = new SingletonDesign();
private static GlobalObject _myGlobalObject;
private SingletonDesign() {
if(_instanceFlag == false) {
_myGlobalObject = new GlobalObject();
_instanceFlag = true;
}
}
public static GlobalObject getModel() {
if(_instanceFlag == false) {
_myGlobalObject = new GlobalObject();
_instanceFlag = true;
}
return _myGlobalObject;
}
public static int parseModel() {
if(_instanceFlag == false) {
_myGlobalObject = new ItemSimilarityModel();
_instanceFlag = true;
}
int val = _myGlobalObject.parseFromFile();
return val;
}
}
I am aware of the fact that every time a request is done, a new thread would be created on my Web – service class (object). My goal, is to have a global SingletonDesign object among all threads, which stays alive in memory, and is created only once.
Despite the fact that the above design seems to be working according to my expectations, I am not really sure if it is correct. So these are my questions:
1) Why do the methods of the SingletonDesign object need to be static? (I have attempted to define them as non-static, but my Singleton object is not initialized properly).
2) The above design is seen from the Wikipedia page on the Singleton Design Pattern. The part that confuses me is the initialization of the _instance field, which I have seen in other Singleton implementations too. Why do we need that object?
3) Does my object stay alive until the server stops? I have made some tests and It seems that it stays alive, but I have to be 100% sure.
Thank you for your time and interest.
The _instance field contains your singleton. You need a static getInstance() method, and your other methods would be instance methods. I don;t think you need the _instanceFlag field at all.
Then you would call it as follows:
SingletonDesign.getInstance().getGlobalObject();
Still, keep in mind that a lot of people (including myself) thing of Singleton as a code-smell. Also, this design is not considered the best way to implement a Singleton in Java, cfr: What is an efficient way to implement a singleton pattern in Java?
The object will stay alive as long as its classloader stays alive.
1) The only static method you actually need in a singleton is the method that returns the instance of the singleton. The method has to be static as you can't instantiate a singleton, and thus the method has to belong to the class instead of the object.
2) A simplified version that might be more easy to begin with:
public class MySingleton {
private static MySingleton instance = null;
private static String aString = null;
private MySingleton( {
aString = new String("Hello, world");
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
public string getMyString() {
return aString;
}
}
3) To my knowledge is stays alive as long as the JVM runs.
As a tip, if you perform some sort of initialization code in the method returning the instance, I'd suggest also declaring the method as synchronized.