Spring has singleton and prototype.
EJB has singleton and stateless.
I've been working on EJB since quite some time and I was of the opinion that singleton in EJB means multiple users cant access the class at the same time. And hence users will be kept waiting until the resource is free. Hence always used stateless.
Coming to Spring there is no equivalent of EJB stateless. Everything is singleton by default or new if used as prototype. So what happens when multiple users are trying to access the same singleton bean concurrently. Are they kept waiting?
Maybe my Java fundamentals are not clear here.
What happens when multiple users try to access the same java singleton class or same method of the same java singleton class. How does it work internally? By java singleton here, I mean a class with a private constructor.
Is using Singleton and Stateless in EJB one and the same?
I've been working on EJB since quite some time and I was of the opinion that singleton in EJB means multiple users cant access the class at the same time. And hence users will be kept waiting until the resource is free. Hence always used stateless.
Multiple threads can use same singleton bean at same time.
https://docs.oracle.com/cd/E19798-01/821-1841/gipsz/index.html
Coming to Spring there is no equivalent of EJB stateless.
Maybe there's no annotation, but the behavior is the same.
Maybe my Java fundamentals are not clear here. What happens when multiple users try to access the same java singleton class or same method of the same java singleton class. How does it work internally? By java singleton here, I mean a class with a private constructor.
As other users said, a class with a private constructor isn't necessarily a singleton.
My preferred singleton is:
private static final UserType INSTANCE = new UserType();
private UserType(){
}
public static UserType get(){
return INSTANCE;
}
Multiple threads can use java singleton, there's no synchronization after instantiation.
Is using Singleton and Stateless in EJB one and the same?
Absolutely not. Stateless beans have a pool of instances. Singleton beans have only one, as java singleton objects. But about concurrency, yes, both will not block threads.
I assume you are talking about a Web application. When a web application running in a servlet container, each user request creates a separate thread with its own Stack. Therefore, methods of a singleton class can be executed by multiple concurrent threads. This is the beauty of Java Virtual machine. This allows concurrent users to access same code without blocking each other.
So what happens when multiple users are trying to access the same
singleton bean concurrently. Are they kept waiting?
Don't mix up synchronized with Singletons. Of course, multiple threads can access a Spring Bean the same time.
What happens when multiple users try to access the same java
singleton class or same method of the same java singleton class.
Nothing, but if your Singleton class has instance or class variables, the threads will access them concurrently.
Related
Generally a lot of applications these days use Spring which takes care of the life cycle of the pojo classes in their application. But what if my application cannot use Spring due to some other issues. How do I go from the Service layer of the application to the DAO layer.
Currently this is what I am doing.
public class MyServiceImpl{
private static MyDAO daoInstance=new MyDAO();
public void someMethod(){
daoInstance.methodToCall();
}
}
public class MyDAO{
public void methodToCall(){
}
}
Keeping the daoInstance in MyServiceImpl as static makes sure that there is only one instance across all ServiceImpl objects. But wouldn't this create concurrency issues if a lot of users access the same piece of code at the same time.
However if I don't keep it static, there would be one daoInstance with each MyServiceImpl object. Wouldn't this leave so many objects in the heap. How would the life cycle of these objects get managed.
I want to understand what is the correct way of navigating from one layer of the application to other layer keeping concurrency, performance and other such factors in mind.
Thanks for any help.
First of all, Service class should not directly call DAO instance.
Interaction between service and DAO should always be through interface in order to make it loosely coupled.
You can create DAO instance as singleton in service class and is thread safe (i.e spring framework uses singleton by default) make sure that the global variables are not used in DAO.
If you make DAO object as singleton then the amount of objects created would be very less which in turn improves the performance.
It depends on your requirement and design.
Do you want to control the resources? then make sure every one acquires them from one location aka singleton.
Do you worry about performance? then make sure you consider all factors including number of threads (concurrent access), I/O, memory usage with in object etc...
It is very tough to balance all non-functional requirements, but ideally while designing the application you have to make trade-off based on requirements and your business objectives.
For more information refer Non-Functional Requirements.
Making DAO instance static will have nothing to do with multy threading. Even if you declared it as instance variable of MyServiceImpl you can still have multiple threads accessing the MyDAO.
I would still declare your MyDAO as instance variable since it will take very little space in memory. The DAO should not have much if any at all instance state. This should also make sure that it will be threads safe as well.
I have a war file deployed in glassfish. We have some stateless session beans and we have 1 synchronized method in it.
However, I am noticing that more than 1 thread is able to enter the synchronized method concurrently. Is it possible that glassfish is instantiating 2 instances of this bean class? Is there any way around this?
Yes, of course it's possible. The spec even mandates that concurrent calls are handled by different instances.: this is one of the services offered by the container: it makes sure that concurrent calls are handled concurrently, and not sequentially, and you're free to implement your sesssion bean without caring about thread-safety (for example, by using instance variables), because the container takes care of it.
What you want is a singleton.
Can i use a singleton within a servlet to share information between diffrent session.
I know that only 1 instance Servlet is running at any time. Calling service method for each incoming request. But how about creating another Singleton class (for eg: ShareSingleton) which calls its getInstance() in the servlets Init() method. This ShareSingleton can carry data that needs to be shared between sessions/reqests.
Is it risky to use such an approach in servlets ?
First..see this for the best approach of singletons: http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
Second: Remember singletons are only single to the JVM. So..if you have more than one JVM running do not expect each singleton to have the same state.
Third: To be safe, I would instantiate the singleton from a listener of the servlet context.
see http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html
define a class in your web.xml and instantiate it there. Your singleton will be created when your webapp starts up rather than when n people hit the service method of your servlet at once.
Yes, you can. Note that the servlet container may use multiple instance of the Servlet object, so you'll have to make sure one object is shared amongst all these instances.
For example, you might do:
private static final Cache<String,String> = //cache
And then use the value in the cache if it's available, or otherwise update the cache with a newly calculated value. Note that the object that is shared must be thread safe.
I have this new mvc project where all beans are default scoped(no prototype or session).
with single application context.
i want to know
by making all beans to be default scoped are we trying to achieve the whole application to be run in single thread?
if so will that make each httprequest(from multiple or same sessions) to be queued until the previous one completes?How to avoid such scenario any advice or link would be helpful.
I am relatively new to spring and java development.
Because Spring beans are typically stateless, you can safely call them from multiple threads. That's how your application works: there is only one instance of every controller, service, DAO, etc. But your servlet container (through Spring) calls these beans from multiple threads - and it's completely thread safe.
In fact in plain servlets the situation is the same - there is only instance of each servlet and it can be accessed by infinite number of threads. As long as this servlet is stateless or properly synchronized.
Do not confuse Spring with stateless session beans in ejb that are pooled and each client gets its own instance from the pool.1
1 - In fact that's a bit dumb - since the beans are stateless by the definition, there is no point in pooling them and preventing concurrent access...
Singleton means that the there will be only one instance of each bean. Generally, such beans are processing elements that carry no state. The methods called on them are passed the context which contains the inputs to work on. Hence the method calls on such singleton beans are inherently thread-safe.
I have a stateless session bean which needs access to a factory class. Is it best to declare this factory class as a static or instance member in the SLSB? Am I correct in saying that, as SLSBs are reused, only one instance of the factory will be created per bean (when going with the instance member option), as opposed to one instance per request?
SLSB instances are pooled, and hence serve potentially many requests over their lifetime, so as you say instance variables are not recreated for each request.
The "natural" way for SLSB is to have each instance independent, no statics, no need for synchronisation between instances. Hence if it's possible I'd have a factory instance per SLSB instance.
Don't assume that an instance of the SLB will not be created per request. The container is within its rights to create one every request; equally, it is also allowed to have only a single instance (I think). More generally, the container will maintain a pool of them.
If instantiating and/or initialising your SLSB is relatively expensive, you should investigate exactly what your container will do, and if possible configure it explicitly to what you want it to do.
Assuming you do that, then there should be no problem with keeping an instance field in the SLSB class.
Instance variables are not recreated as long as the SLSB is reused from the pool. The lifecycle of SLSB is rather simple: create an instance, use it n times to attend n requests, and eventually throw it away. All these actions are performed by the container. So in the creation process of the bean (controlled by us) we can initialize these instance variables. But never modify the contents of these variables once they are initialised in order to avoid side effects.
You can use static instances if you wish to, but bear in mind that you must handle the synchronization issues by hand; and furthermore, you are constrained to a local factory.
A very elegant solution is provided by EJB 3.1 with the #Singleton EJBs.