Persistent Singleton Object for Java Web Service - 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.

Related

How to avoid the performance overhead of using volatile in singleton pattern?

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

lateinit, lazy and singleton pattern in kotlin

I'm trying to convert some part of my project from java to kotlin. One of it is a singleton manager class. The java class looks like this
public class Manager {
private static volatile Manager Instance = null;
private static final Object InstanceLock = new Object();
private Manager(Object1 object1, Object2 object2, Object3 object3){//...};
public static boolean isInitialized(){
synchronized(InstanceLock){
return Instance == null;
}
}
public static void initialize(Object1 object1, Object2 object2, Object3 object3){
if(Instance == null){
synchronized(InstanceLock){
if(Instance == null){Instance = new Manager(object1, object2, object3};
}
}
}
public static getInstance(){
Precondition.checkNotNull(Instance, msg...);
return Instance;
}
}
Also, I decompiled .kt back to java. In the companion class I get the following code.
public static final class Companion {
#Nullable
public final Manager getInstance() {
return Manager.instance;
}
private final void setInstance(Manager var1) {
Manager.instance = var1;
}
private final Object getInstanceLock() {
return Manager.InstanceLock;
}
public final boolean isInitialized() {
Object var1 = Manager.Companion.getInstanceLock();
synchronized(var1){}
boolean var4;
try {
var4 = Manager.Companion.getInstance() == null;
} finally {
;
}
return var4;
}
public final void initialize(#NotNull String string1, #NotNull String string2) {
Intrinsics.checkParameterIsNotNull(string1, "string1");
Intrinsics.checkParameterIsNotNull(string2, "string2");
if (((Manager.Companion)this).getInstance() == null) {
Object var3 = ((Manager.Companion)this).getInstanceLock();
synchronized(var3){}
try {
if (Manager.Companion.getInstance() == null) {
Manager.Companion.setInstance(new Manager(string1, string2, (DefaultConstructorMarker)null));
}
Unit var5 = Unit.INSTANCE;
} finally {
;
}
}
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
1) How do I achieve thread safety, singleton by using lateinit or lazy inside the kotlin companion object ? As I can see, the decompiled java code has a synchronized call in initialize function but nothing in the synchronize body.
2) I think kotlin object/lazy comes with thread safety guarantee, how do I take advantage of it in the double-checked locking pattern ?
3) Is there a better pattern than double-checked locking pattern? Assuming the constructor does need arguments.
4) Since I'm trying to make the impact of converting this manager class to kotlin file as small as possible (this Manager file is supposed to work with the rest of java code), what is the best approach ? I do notice I have to add #Jvmstatic or #Jvmfield in some other variables or functions inside of companion object so that I don't have to update other java file that has call to these static field in manager.
5) Additional question, what if this manager is now working in pure kotlin environment, what's the best practice of implementing a singleton class with multiple arguments ?
The first answer does not address the synchronization, which, btw, is still an under appreciated complexity. There are still a ton of people running around saying simply do double-checked locking. But there are some pretty compelling arguments that show that DCL does not always work.
Interestingly, though, I had this same issue recently and found this article. While I did not like this the first time I found it, I revisited it a few times and warmed up to it, in large part because:
the author went and got code from the Kotlin stdlib
the result is a parameterized mechanism that while kind of ugly affords reuse, which is pretty compelling
Notice that the major issues are all broached in this treatment:
synchronization
complex initialization
parameterized initialization (crucial in Android, where the Context god object is ineradicable)
resulting compiled code
In short I think this is pretty much the first and last word on this topic, amazingly, found on Medium.
I don't have answer to all of your questions, but there is a defined way to create a singleton class in Kotlin.
Instead of class prefix in front of the class name, use object.
For example,
object Manager {
// your implementation
}
This make this class singleton and you can directly use this from Java like Manager.getInstance() (I didn't remeber the exact syntax but this should work) . Kotlin creates it for you.
You can check this for more reference.
Hope it will help you a little.

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.

What if the benefit of using a final instance in the classic singleton pattern (if any)?

In the below snippet, Singleton1#INSTANCE is not final, while Singleton2#INSTANCE is:
public class Singleton1 {
private static Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
public class Singleton2 {
private static final Singleton2 INSTANCE = new Singleton2();
private Singleton2() {
public static Singleton2 getInstance() {
return INSTANCE;
}
}
What is the benefit of Singleton2 over Singleton1 (if any)?
There is none, Java wise. Class initialization happens atomically, within locks. No thread will be able to see Singleton1#INSTANCE partially created.
At this point, use final to clarify (to developers) that this field should not change.
I'm fairly certain that the answer is none for performance. It could prevent a bug if someone were to try and modify the reference at some point during the maintenance cycle.
final is basically used for two purposes in java -
1) For immutability - If a field is final, then it can only be initialized only once. So, if INSTANCE is not final then you can reinitialize creating one more object but this can only be done as constructor is private. So, basically final can avoid any other bugs which can be introduced at later stage as mentioned by Elliott.
2) To ensure that object is properly constructed before publishing (it is in context of multithreading) but since we are instantiating the INSTANCE on class loading (eager loading). It will not cause any issues. It will be created long before it will be used.

How can I know whether an instance of a class already exists in memory?

How can I know whether an instance of a class already exists in memory?
My problem is that don't want read method if exist instance of Class
this is my code
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.
If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:
This is the common singleton idiom:
public class PNLSpcMaster {
/**
* This class attribute will be the only "instance" of this class
* It is private so none can reach it directly.
* And is "static" so it does not need "instances"
*/
private static PNLSpcMaster instance;
/**
* Constructor make private, to enforce the non-instantiation of the
* class. So an invocation to: new PNLSpcMaster() outside of this class
* won't be allowed.
*/
private PNLSpcMaster(){} // avoid instantiation.
/**
* This class method returns the "only" instance available for this class
* If the instance is still null, it gets instantiated.
* Being a class method you can call it from anywhere and it will
* always return the same instance.
*/
public static PNLSpcMaster getInstance() {
if( instance == null ) {
instance = new PNLSpcMaster();
}
return instance;
}
....
}
Usage:
private void jButton (java.awt.event.ActionEvent evt) {
// You'll get the "only" instance.
PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
jtabbedPanel.addTab("reg",pnlSpc);
}
Or directly:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.
You could read more about it: Why singletons are controversial
I think you're after the singleton pattern.
Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.
The following example is unreliable, although it could provide you with a correct enough answer if you use the hasAtleastOne() method.
class Example {
private static int noOfInstances = 0;
public Example() {
noOfInstances++;
}
public static boolean hasAtleastOne() {
if(noOfInstances > 0)
return true;
else
return false;
}
protected void finalize() throws Throwable {
noOfInstances--;
}
}
The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.
Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.
The Dispose Pattern
You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.
There isn't a reasonable way to find out whether or not an instance of a particular class already exists.
If you need to know this information, create a static boolean field and set it from the constructor:
class MyClass {
private static bool instanceExists = false;
public MyClass() {
MyClass.instanceExists = true;
}
}
For classes that have a notion of identity, the Identity Map pattern applies.

Categories

Resources