Using Singleton to Share a Variable - java

I have been having a hard time understanding how to use a singleton to share a common variable. I am trying to make a blackberry app which has two entry points which need to share a common variable, iconCount. I have been advised to use a singleton with the RunTimeStore API by someone on a forum. Googling around eventually leads to:
http://docs.blackberry.com/en/developers/deliverables/17952/CS_creating_a_singleton_by_using_rutnime_store_1554335_11.jsp
I have been a few pages deep in Google but I still can`t understand what this does and how to implement it. My current understanding is that a singleton will create a "global variable" somehow through the code:
class MySingleton {
private static MySingleton _instance;
private static final long GUID = 0xab4dd61c5d004c18L;
// constructor
MySingleton() {}
public static MySingleton getInstance() {
if (_instance == null) {
_instance = (MySingleton)RuntimeStore.getRuntimeStore().get(GUID);
if (_instance == null) {
MySingleton singleton = new MySingleton();
RuntimeStore.getRuntimeStore().put(GUID, singleton);
_instance = singleton;
}
}
return _instance;
}
}
And another question would be how would I create a variable from this singleton? I need to declare variable iconCount = 0 at the beginning and then be able to use it. Would declaring it be something like
Integer iconCount = (Integer) RuntimeStore.getInstance();
? This is very new to me as I have just started Java so if anyone could explain this keeping in mind you're communicating with a novice I would be very grateful. Thanks in advance!

You would call
MySingleton.getInstance()
to get the instance in your app. The point is that getInstance is controlling access to the underlying object.
Also, you should make your constructor private, so it's only accessible in that file.
To define a property on you singleton class, just declare a non-static property. Each instance of the class will have its own copy, but you are controlling the creation of the objects, so their should only ever be 1 (per JVM). So
class MySingleton {
private static MySingleton _instance;
private static final long GUID = 0xab4dd61c5d004c18L;
private Integer iconCount; // non-static method, add a public getIconCount below
...
}
and then you can access it via
MySingleton.getInstance().getIconCount();

They mean please make sure that user initializing MySingleton class just onetime so you will not have problem with multiple instances and initialize two count in the same time. I mean from multiple instance something like below:
Mysingleton single = new Mysingleton();
Mysingleton single2 = new Mysingleton();
Because both initilaization can have diffetent count. You need something like this:
public class IconManager {
private static iconManager _instance;
private static final long GUID = 0xab4dd61c5d004c18L;
private static int count = 0;
// constructor
IconManager() {
}
public static IconManager getInstance() {
if (_instance == null) {
_instance = (IconManager) RuntimeStore.getRuntimeStore().get(GUID);
if (_instance == null) {
IconManager singleton = new IconManager();
RuntimeStore.getRuntimeStore().put(GUID, singleton);
_instance = singleton;
}
}
return _instance;
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
this.count = count;
}
}
and after you can create an instance for the class:
public static void main(String[] args){
IconManager iconManager = IconManager.getInstance();
iconManager.setCount(iconmanager.getCount() + 1);
}
So application will do first validation, if there is already an instance it will update existing one, if not than it will create new one.

You can't cast your MySingleton class to Integer.
And in your example you don't use your singleton but RuntimeStore !
You can use an integer field of your class Singleton, initalized to 0 in the constructor of your singleton (private constructor) and get it by doing :
MySingleton.getInstance().getIntegerField()
here is a detailled description of the singleton pattern :
http://en.wikipedia.org/wiki/Singleton_pattern
I think you misunderstand the use of the singleton. the singleton is not injected in your RuntimeStore, it is a classic java object. The only subtile think to know about a singleton is that its constructor is private and the class MySingleton can have only one instance which is always returned when your singleton.getInstance() is called

Related

singleton pattern in storm topology

I have written a storm topology, and set its workers number to 1.
So, I think all of its components should be run in the same process. And I want to share a common object between multiple components in the topology, so I use singleton pattern:
1, I initialize the singleton object when the unique spout has been opened.
2, Then, I use the singleton object in other components by calling the function getInstance().
But, I found that I will get the different objects between different components.
Thanks for your replies. The key code of the problem are listed as follows:
The singleton class code:
public class TraceApplicationContext {
private volatile static TraceApplicationContext instance = new TraceApplicationContext();
private TraceApplicationContext() {
}
public static TraceApplicationContext getInstance() {
return instance;
}
}
The SpoutA class code:
public class SpoutA extends BaseRichSpout {
public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
TraceApplicationContext.getInstance().init();
}
}
The BoltA code:
public class BoltA extends BaseRichBolt {
private static JedisCluster jedisCluster = TraceApplicationContext.getInstance().getJedisCluster();
}
The BoltB code:
public class BoltB extends BaseRichBolt {
private static JedisCluster jedisCluster = TraceApplicationContext.getInstance().getJedisCluster();
}
After initialized the TraceApplicationContext singleton object in SpoutA, I check the object return by TraceApplicationContext.getInstance().getJedisCluster(), it's not null. But I check it in BoltA and BoltB, the object returned by TraceApplicationContext.getInstance().getJedisCluster() is null.
Have anyone met the same problem or know what's wrong with such problem?
Please help!
Thank you!
If you can't use enum as #Jorge_B says you can use a synchronized block in the getInstance() method
public class MySingleton {
private static volatile MySingleton instance;
private MySingleton() { ... }
public static MySingleton getInstance() {
if (instance == null) {
synchronized(MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
}
http://en.wikipedia.org/wiki/Singleton_pattern
EDIT
But it's may be not a singleton problem
The fact that the getJedisCluster() return different values doesn't mean that it's not the same singleton but rather that the state of the singleton has changed
try to make the jedisCluster final inside the singleton (a final property couldn't be changed but must be initialized inside the constructor)
private final JedisCluster jedisCluster;
if you can't try to track when the jedisCluster is changed : use of setter...
If you have made sure all your processes run in the same JVM, try to implement your Singleton as an Enumeration of a single element. This should solve every possible concurrence problem with the object initialization.
For example:
An implementation like
public class MySingleton {
private static MySingleton instance;
private MySingleton() { ... }
public static MySingleton getInstance() {
if (instance == null) { instance = new MySingleton() }
return instance;
}
}
Is prone to concurrency problems. However, one like this
public enum MySingleton {
INSTANCE;
private MySingleton() {...}
}
Should work everywhere.
As with my experience, I was using singleton cassandra session object, as well as singleton for application properties in my storm topology.
Since these singleton objects do not have any varying state , even when we have multiple WorkerProcess(WP) (ie one JVM per WP), each WP will have a copy of the singleton and can be made use without issue.
As far as best practice is concerned, its better to set the static singletons to the config object while submitting the topology, and the prepare method will supply it to individual tasks.
https://groups.google.com/forum/#!topic/storm-user/rWeQpGEnT9Q

What is the right singelton implementation and why

What is the difference between two implementation in java, which is the correct and why?
class Singleton
{
private static Singleton instance = new Singleton();
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
public static Singleton getInstance()
{
return instance;
}
}
Or
class Singleton
{
private static Singleton instance;
static
{
instance = new Singleton();
}
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
public static Singleton getInstance()
{
return instance;
}
}
First coming to your question,
AFAIK, both code snippets are same. I don't see any difference.
However, As other answers have suggested there are better ways to create Singleton implementation. But that would be bit off-topic to your question and internet (google) is your best friend to find it out.
No difference. In both cases you are eagerly creating an instance and by the time getInstance() is called, the instance is ready.
But if you are looking for a easy and good implementation of singleton,
Better use an enum to implement Singleton
public enum Singleton {
INSTANCE;
}
My answer bases on this article about singleton: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Your first example should always work but does not allow lazy init.
In a single threaded environment you could implement a singleton like in "my" first example.
In a multi-threaded environment with Java 1.5 and referenced mutable objects you could use "my" second example.
Useful stackoverflow answer/articles:
What is an efficient way to implement a singleton pattern in Java?
Implementing the singleton pattern in Java
Singleton class in java
Example 1:
class SingleSingleton {
private Helper helper = null;
public Helper getHelper() {
if (helper == null)
helper = new Helper();
return helper;
}
}
Example 2:
class MultiSingletonJDK5 {
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null)
helper = new Helper();
}
}
return helper;
}
}
I hope this helps. If not, give us some details or more background.
Both implementations are not correct, also static qualifier are not quite good practice at all :)
There are my suggestion of Singletns:
public final class LazySingleton {
private static volatile LazySingleton instance = null;
// private constructor
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (instance == null) {
synchronized (LazySingleton.class) {
instance = new LazySingleton();
}
}
return instance;
}
}
public class EagerSingleton {
private static volatile EagerSingleton instance = null;
// private constructor
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
if (instance == null) {
synchronized (EagerSingleton.class) {
// Double check
if (instance == null) {
instance = new EagerSingleton();
}
}
}
return instance;
}
}
Generally, Singleton design pattern concept is based on having only single instance of your class. This could be reached through two main aspects:
1) Having a private constructor for your class to prevent any outer class to call it and re-create the instance. This could be reached as the following:
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
2) Having a static method that allow you to retrieve the initialized instance or initialize it if it is not initialized yet as #Awfully Awesome mentioned in his answer:
public static Singleton newInstance()
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
Both the mentioned methods are not the right way of applying Singleton pattern.
Here's the right way. The Lazy-Instantiation way:
public class Singleton
{
private static Singleton singleton;
private Singleton()
{
}
public synchronized static Singleton getInstance()
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
}
The getInstance() method lazily instantiates Singleton object when its called the first time. So the Singleton object isn't present in the memory, till the moment its required.

How does Singleton behave when two threads call the "getInstance()" at the same time?

How does Singleton behave when two threads call the "getInstance()" at the same time? What are the best practices to protect it?
This is only an issue at all if you use lazy initialization on the singleton. If you use eager initialization then the JVM guarantees to sort it all out for you.
For lazy initialization you need to either synchronize (although you can make it volatile and use double-check locking to avoid synchronized blocks all the time) or embed it within an inner class where it is not lazy initialized.
peter.petrov's answer now covers most of the options well, there is one final approach to thread safe lazy initialization though that is not covered and it is probably the neatest one.
public class Singleton {
// Prevent anyone else creating me as I'm a singleton
private Singleton() {
}
// Hold the reference to the singleton instance inside a static inner class
private static class SingletonHolder {
static Singleton instance = new Singleton();
}
// Return the reference from inside the inner class
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Java does lazy loading on classes, they are only loaded when first accessed. This applies to inner classes too...
Firstly, two threads can't call the method at the "same time" - one will be deemed to call it first... called a "race condition".
Next, any properly implemented singleton will handle a race condition cleanly. IMHO, this is the cleanest way to implement a thread-safe singleton without synchronization:
public class MySingleton {
private static class Holder {
static final MySingleton INSTANCE = new MySingleton ();
}
public static MySingleton getInstance() {
return Holder.INSTANCE;
}
// rest of class omitted
}
This is called the initialization-on-demand holder idiom.
1) If you want lazy init, I think a good practice is to synchronize the getInstance body on a private static final Object instance which is member of the same class (you may name it LOCK e.g.).
2) If you don't need lazy init you can just instantiate your singleton instance at class load time. Then there's no need of any synchronization in getInstance.
Sample of 1) without using DCL (double-checked locking)
Note 1: This one avoids the complexity of using DCL by paying some extra price with respect to performance.
Note 2: This version is OK on JDK < 5 as well as on JDK >= 5.
public class Singleton {
private static final Object LOCK = new Object();
private static Singleton instance = null;
public static Singleton getInstance(){
synchronized(LOCK){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
private Singleton(){
// code to init this
}
}
Sample of 1) using DCL
Note 1: This is OK on JDK >= 5 but not on JDK < 5.
Note 2: Note the volatile keyword used, this is important.
public class Singleton {
private static final Object LOCK = new Object();
private static volatile Singleton instance = null;
public static Singleton getInstance(){
if (instance == null){
synchronized(LOCK){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
private Singleton(){
// code to init this
}
}
Sample of 2)
Note 1: This is the most simple version.
Note 2: Works on any JDK version.
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
private Singleton(){
// code to init this
}
}
References:
1) Older JDK versions (JDK < 5)
http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html
2) More recent updates on DCL
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
public class Singleton{
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
When the getInstance method is invoked for the first time, it reads Holder.INSTANCE for the first time, causing the Holder class to get initialized. The beauty of this idiom is that the getInstance method is not synchronized and performs only a field access.This is called lazy initialization. You might think that Holder class should also be loaded by the class loader when Singleton class is loaded because Holder class is static. Loading a top-level class does not automatically load any nested types within,Unless there's some other initialization that occurs during the top-level initialization, like if your top-level class has a static field that needs to be initialized with a reference to an instance of the nested class.
Synchronize access of getInstance.
Class TestSingleton {
private static volatile TestSingleton singletonObj = null;
private TestSingleton (){ // make constructor private
}
public static getInstance(){
TestSingleton obj = singletonObj ;
if(obj == null) {
synchronized(lock) { // while we were waiting for the lock, another
obj = instance; // thread may have instantiated the object
if(obj == null) {
obj = new TestSingleton();
instance = obj ;
}
}
}
public doSomeWork(){ // implementation
}
}

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

Java Singleton and Synchronization

Please clarify my queries regarding Singleton and Multithreading:
What is the best way to implement Singleton in Java, in a multithreaded
environment?
What happens when multiple threads try to access getInstance()
method at the same time?
Can we make singleton's getInstance() synchronized?
Is synchronization really needed, when using Singleton classes?
Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:
Draconian synchronization:
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
This solution requires that every thread be synchronized when in reality only the first few need to be.
Double check synchronization:
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance;
if (r == null) {
synchronized (lock) { // While we were waiting for the lock, another
r = instance; // thread may have instantiated the object.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.
Initialization on Demand:
private static class InstanceHolder {
private static final YourObject instance = new YourObject();
}
public static YourObject getInstance() {
return InstanceHolder.instance;
}
This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.
This pattern does a thread-safe lazy-initialization of the instance without explicit synchronization!
public class MySingleton {
private static class Loader {
static final MySingleton INSTANCE = new MySingleton();
}
private MySingleton () {}
public static MySingleton getInstance() {
return Loader.INSTANCE;
}
}
It works because it uses the class loader to do all the synchronization for you for free: The class MySingleton.Loader is first accessed inside the getInstance() method, so the Loader class loads when getInstance() is called for the first time. Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety.
It's like magic.
It's actually very similar to the enum pattern of Jhurtado, but I find the enum pattern an abuse of the enum concept (although it does work)
If you are working on a multithreaded environment in Java and need to gurantee all those threads are accessing a single instance of a class you can use an Enum. This will have the added advantage of helping you handle serialization.
public enum Singleton {
SINGLE;
public void myMethod(){
}
}
and then just have your threads use your instance like:
Singleton.SINGLE.myMethod();
Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.
Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.
There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.
Enum singleton
The simplest way to implement a Singleton that is thread-safe is using an Enum
public enum SingletonEnum {
INSTANCE;
public void doSomething(){
System.out.println("This is a singleton");
}
}
This code works since the introduction of Enum in Java 1.5
Double checked locking
If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.
Early loading Singleton (works even before Java 1.5)
This implementation instantiates the singleton when the class is loaded and provides thread safety.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void doSomething(){
System.out.println("This is a singleton");
}
}
You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.
public class MySingleton {
private static final MySingleton instance;
static {
instance = new MySingleton();
}
private MySingleton() {
}
public static MySingleton getInstance() {
return instance;
}
}
What is the best way to implement Singleton in Java, in a multithreaded environment?
Refer to this post for best way to implement Singleton.
What is an efficient way to implement a singleton pattern in Java?
What happens when multiple threads try to access getInstance() method at the same time?
It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.
Refer to this question for more details:
Why is volatile used in this example of double checked locking
Can we make singleton's getInstance() synchronized?
Is synchronization really needed, when using Singleton classes?
Not required if you implement the Singleton in below ways
static intitalization
enum
LazyInitalaization with Initialization-on-demand_holder_idiom
Refer to this question fore more details
Java Singleton Design Pattern : Questions
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis () {...}
}
Source : Effective Java -> Item 2
It suggests to use it, if you are sure that class will always remain singleton.

Categories

Resources