As per my knowledge singleton Object is not thread safe and session Factory singleton object is thread safe. How this possible, Please explain someone.
2 Answers
The singleton pattern is neither thread-safe nor not thread-safe per se. You have to take a look at your specific implementation. The major question is, does it manage state?
If so then you will make sure that no more than one thread is ever allowed to change the state at the same time. That is the same problem global variables are suffering from regarding thread-safety. But there are mechanisms to ensure this safety, one is called mutual exclusion. The event of two threads concurrently modifying the same variable is one the problematic events, there are more to be aware of. Like two threads sequentially modifying a variable, then the question is whos answer counts.
Mutually exclusive events in general and a specific explanation in the java context can be found here (Mutually exclusive events) and here (Oracle concurrency guide) respectively. Global variables are explained here. Stateless and stateful are also good terms to look at regarding concurrency, parallelism and thread-safety.
Back to your question: A factory usually doesn't introduce any state and though can being shared freely between several threads. Instances produced by the factory most probably are stateful and should only be shared between threads after having made them thread-safe.
Important Note: But don't get me wrong here. Don't forget to always check the implementation of your singletons! In java you can introduce annotations to document your investigations and mark specific code elements as thread-safe. There exist packages wich already define commonly usable annotations to document such behavior, take a look at the apache org.apache.http.annotation. When you use an API it is a good idea to inspect the documentation for such hints.
Session factory object is also implemented using the singleton
design pattern.
singleton design pattern can be made as thread safe
.
and they have implemented singleton with thread safe for session factory.
when we implement singleton
we should make sure whether we need thread safe or not and we should implement acordingly.
see the various implementation of singleton in my blog under design pattern

- 2,686
- 1
- 18
- 27