How to synchronize static method in java - java

I come up with this question when implementing singleton pattern in Java. Even though the example listed below is not my real code, yet very similar to the original one.
public class ConnectionFactory{
private static ConnectionFactory instance;
public static synchronized ConnectionFactory getInstance(){
if( instance == null ){
instance = new ConnectionFactory();
}
return instance;
}
private ConnectionFactory(){
// private constructor implementation
}
}
Because I'm not quite sure about the behavior of a static synchronized method, I get some suggestion from google -- do not have (or as less as possible) multiple static synchronized methods in the same class. I guess when implementing static synchronized method, a lock belongs to Class object is used so that multiple static synchronized methods may degrade performance of the system.
Am I right? or JVM use other mechanism to implement static synchronized method? What's the best practice if I have to implement multiple static synchronized methods in a class?
Thank you all!
Kind regards!

The best approach (which makes as few changes in your code as possible) is to do like this:
public class ConnectionFactory{
private static ConnectionFactory instance = new ConnectionFactory();
public static ConnectionFactory getInstance(){
return instance;
}
private ConnectionFactory(){
}
}
As you can see, there is no real need in getInstance method now, so you can simplify the code to:
public class ConnectionFactory{
public static final ConnectionFactory INSTANCE = new ConnectionFactory();
private ConnectionFactory(){
}
}
UPD about synchronization: the best way is synchronizing on a lock which is not visible to outer classes, i.e.:
public class ConnectionFactory{
private static final Object lock = new Object();
public static void doSmth() {
synchronized (lock) {
...
}
}
public static void doSmthElse() {
synchronized (lock) {
...
}
}
}
There are many discussions about "why synchronizing on this is a bad idea" (like this one), I think that the same is actual for synchronizing on class.

There are a couple of ways you can create a singleton.
One recommended way is to use an enum (guaranteed to only create one instance):
public enum ConnectionFactory {
INSTANCE;
}
Or you can create it statically when the class loads:
public class ConnectionFactory {
private static ConnectionFactory INSTANCE = new ConnectionFactory();
private ConnectionFactory() {}
public static ConnectionFactory getInstance() {
return INSTANCE;
}
}
If you need to lazily load it you can use this idiom (rather than the double checked locking anti-pattern )
public class ConnectionFactory {
private static class ConnectionFactoryHolder {
private static ConnectionFactory INSTANCE = new ConnectionFactory();
}
public static ConnectionFactory getInstance() {
return ConnectionFactoryHolder.INSTANCE;
}
}

Yes, static methods are synchronized on their class object. I wouldn't worry about performance here, as probably this will not be your performance hot spot. Do it simple, optimize when and where you need to.

Static synchronized methods use the lock on the class. In the case of your example it would be accessing the lock on the ConnectionFactory class object. Best practice is not to hold onto locks for longer than you have to. Whether you have multiple synchronized methods is not a problem in itself.

Effective Java recommends using Enums to create singleton. So you code would look something like this:
public enum ConnectionFactory{
INSTANCE;
// Other factory methods go here.
}
}

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 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.

Different ways to write singleton in Java

The classic of writing a singleton in java is like this:
public class SingletonObject
{
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
private static SingletonObject ref;
}
and we can add synchronized keyword if we need it to run in multithreaded cases.
But I prefer to write it as:
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
return ref;
}
private static SingletonObject ref = new SingletonObject();
}
which I think is more concise, but strangely I didn't see any sample code written in this way, is there any bad effects if I wrote my code in this way?
The difference between your code and the "sample code" is that your singleton is instantiated when the class is loaded, while in the "sample" version, it is not instantiated until it is actually needed.
In the second form, your singleton is eagerly loaded and this is actually the preferred form (and the first one isn't thread-safe as you mentioned it yourself). Eager loading is not a bad thing for production code but there are contexts where you might want to lazy load your singletons, as discussed by the author of Guice, Bob Lee, in Lazy Loading Singletons that I'm quoting below:
First, why would you want to lazy load
a singleton? In production, you
typically want to eagerly load all
your singletons so you catch errors
early and take any performance hit up
front, but in tests and during
development, you only want to load
what you absolutely need so as not to
waste time.
Before Java 1.5, I lazy loaded
singletons using plain old
synchronization, simple but effective:
static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
Changes to the memory model in 1.5
enabled the infamous Double-Checked
Locking (DCL) idiom. To implement DCL,
you check a volatile field in the
common path and only synchronize when
necessary:
static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
But volatile isn't that much faster
than synchronized, synchronized is
pretty fast nowadays, and DCL requires
more code, so even after 1.5 came out,
I continued using plain old
synchronization.
Imagine my surprise today when Jeremy
Manson pointed me to the
Initialization on Demand Holder
(IODH) idiom which requires very
little code and has zero
synchronization overhead. Zero, as in
even faster than volatile. IODH
requires the same number of lines of
code as plain old synchronization, and
it's faster than DCL!
IODH utilizes lazy class
initialization. The JVM won't execute
a class's static initializer until you
actually touch something in the class.
This applies to static nested classes,
too. In the following example, the
JLS guarantees the JVM will not
initialize instance until someone
calls getInstance():
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
[...]
Update: Credit where credit is due, Effective Java (copyright
2001) detailed this pattern under item
48. It goes on to point out that you still have to use synchronization or
DCL in non-static contexts.
I also switched singleton handling in
my framework from synchronization to
DCL and saw another 10% performance
boost (compared to before I started
using cglib's fast reflection). I only
used one thread in my micro-benchmark,
so the boost to concurrency could be
even greater given that I replaced a
heavily contended lock with a
relatively fine grained volatile field
access.
Note that Joshua Bloch now recommends (since Effective Java, 2nd ed) to implement singletons using a single-element enum as pointed out by Jonik.
Well, in the latter case the singleton object gets created before it is ever needed, but in most cases that's probably not horribly bad.
By the way, Joshua Bloch recommends (in Effective Java, 2nd ed, item 3) implementing singletons using a single-element enum:
public enum SingletonObject {
INSTANCE;
}
He gives the following justification:
[...] it is more concise, provides serialization
machinery for free, and provides an
ironclad guarantee against multiple
instantiation, even in the face of
sophisticated serialization or
reflection attacks. While this
approach has yet to be widely adopted,
a single-element enum type is the best
way to implement a singleton.
I would say the latter code is the more standard pattern, actually. Your first version isn't thread-safe. Ways of making it thread-safe include synchronizing on every access, or very carefully making it use double-checked locking (which is safe as of the Java 5 memory model, so long as you get it right).
Note that due to classes being initialized lazily, your latter code would still only create an object unnecessarily if you called static methods on the class without wanting to create the instance.
There's a pattern using a nested class to do the initialization which can make this lazier, but personally the second form almost always does well enough for me on its own.
There are more details of this in Effective Java, but I don't have it with me to find the item number, I'm afraid.
I think your problem is that you're mixing singleton and lazy initialization. A singleton can be implemented with different initialization strategies:
initialization on class loading
lazy initialization that uses double checked locking
lazy initialization with single checking (with possible repeated initialization)
lazy initialization that uses the class loader (holder class idiom)
All these approaches are discussed in Effective Java 2nd Item 71: Use lazy initialization judiciously.
the second way will solve multi-threading issue but will always create the Singleton even when you don't need it. The best way to do it is to create a Nested class.
public class singleton
{
private singleton()
{
System.out.println("I'am called only when it's needed");
}
static class Nested
{
Nested() {}
private static final singleton instance = new singleton();
}
public static singleton getInstance()
{
return Nested.instance;
}
public static void main(String [] args)
{
singleton.getInstance();
}
}
The best way to write a singleton class is given below .Please try it
public final class SingeltonTest {
/**
* #param args
* #return
*/
private static SingeltonTest instance = null;
private SingeltonTest() {
System.out.println("Rahul Tripathi");
}
public static SingeltonTest getInstance() {
if (instance == null) {
synchronized (SingeltonTest.class) {
if (instance == null)
instance == new SingeltonTest();
}
}
return instance;
}
}
Different ways to implement singleton pattern in java is as follows
public class SingletonClass {
private SingletonClass= null;
public static SingletonClass getInstance() {
if(SingletonClass != null) {
SingletonClass = new SingletonClass();
}
}
}
This is not thread safe. The following are thread safe implementation of singleton design pattern
1. Draconian synchronization
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
2.Double check synchronization
Reference
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;
}
3. Initialization-on-demand holder idiom
Reference
public class Something {
private Something() {}
private static class LazyHolder {
static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
4. Other one is using enum
public enum Singleton {
SINGLE;
public void myMethod(){
}
}
// Lazy loading enabled as well as thread safe
class Singleton {
private static class SingletonHolder {
public static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
I am declaring private constructor and static block so the purpose of static block is it will execute only once and inside a static block I am creating an object so constructor will be invoked only once.
class Demo {
static Demo d=null;
static {
d=new Demo();
}
private Demo(){
System.out.println("Private Constructor");
}
void add(){
System.out.println("Hello I am Non-Static");
}
static Demo getInstance(){
return d;
}
}
I agree with Anon, and in the case where I always want to instantiate the singleton I would use
public class SingletonObject
{
public static SingletonObject REF = new SingletonObject();
private SingletonObject()
{
// no code req'd
}
}

Singleton Factory method

Is it possible to have a singleton in a factory method? I have many domains using the factory method. How do I work around with this. Please help me with an example.
In this example, I believe you would want to synchronize your getInstance() method to ensure two threads do not simultaneously enter it. Otherwise two threads can end up inside the block where the singleton is instantiated which is very problematic. The only issue with this solution is you pay a premium for the synchronization of the method every time getInstance() is called.
Example:
public static synchronized Singleton getInstance()
{
// since whole method is synchronized only 1 thread can
// enter the following block ensuring only one instance
// is ever created. however we pay a synchronization
// penalty every time this method is called.
if(mInstance==null) {
mInstance=new Singleton();
}
return mInstance;
}
Alternatively you could also switch to use eager initialization of the singleton instance rather than lazy initialization if initializing is cheap which guarantees concurrency as well as not paying a synchronized penalty for invoking the getInstance() method.
Example:
// no synchronization penalty, but penalty for eager init
private static Singleton mInstance = new Singleton();
public static Singleton getInstance()
{
return mInstance;
}
The most optimized approach is to use double-checked locking, something you need Java 1.5 or newer to use reliably due to differing implementations of the volatile keyword in 1.4 or older JVMs (please refer to "Head First Design Patterns" chapter 5 p.182 published by O'Reilly Media, Inc. -- that is where I first read about this.)
Example:
private volatile static Singleton mInstance;
private Singleton(){}
public static Singleton getInstance()
{
if(mInstance==null) {
synchronized (Singleton.class) {
// only pay synchronization penalty once
if(mInstance==null){
mInstance=new Singleton();
}
}
}
return mInstance;
}
"...create an interface for objects that create instances of the Singleton class. This is essentially a combination of the Abstract Factory, Factory Method and Functor patterns in the GoF book."
/**
* An interface defining objects that can create Singleton
* instances.
*/
public interface SingletonFactoryFunctor {
/**
* #return An instance of the Singleton.
*/
public Singleton makeInstance();
}
You should call your Singleton getInstance() method from the factory method. The getInstance() logic should handle the details of returning the one instance of the Singleton.
Singleton you can implement like:
public class Singleton {
private static Singleton mInstance;
private Singleton(){}
public static Singleton getInstance()
{
if(mInstance==null){
mInstance=new Singleton();
}
return mInstance;
}
}
This class you can return in every Factory methode you want, like mepcotterell described before.
This example is not a formal Factory Pattern (GoF) but is still helpful if you use it like a Static Factory Method
abstract class Product {}
class ConcreteProduct extends Product{}
class ProductSupportFactory {
private static ProductSupportFactory instance = null;
private ConcreteProduct product = null;
static {
instance = new ProductSupportFactory();
}
private ProductSupportFactory() {
product = new ConcreteProduct(); //object initialization
}
public static ProductSupportFactory getInstance(){
return instance;
}
public ConcreteProduct getProduct() {
return product;
}
public void setProduct(ConcreteProduct product) {
this.product = product;
}
}
public class ProductConsumer {
public static void main(String args[]){ //client
ConcreteProduct uniqueInstance = ProductSupportFactory.getInstance().getProduct();
ConcreteProduct sharedInstance = ProductSupportFactory.getInstance().getProduct(); //same object hash
}
}

Categories

Resources