What's the point of using #Scoped with EJBs? - java

Usually I'm using #RequestScoped or #SessionScoped (from javax.enterprise.context) to inject objects (for instance in faces beans) using #Inject.
I am also using EJBs. As I understood, a set of stateless EJB copies (pool) is used to be injected to objects. The reason there are many copies is to ensure one instance of EJB isn't accessed concurrently. When speaking about stateful EJBs (again as I understood), one instance of such is bound to concrete injection point. And they are injected using #EJB (the stateless ones too).
Frequently I can see on the web examples of using #Stateless or #Stateful in conjunction with #Scoped. What is the meaning of them?
Edit: (trying to clarify as no one responded to this moment):
I'm especially interested whether such scoped annotations change anyhow (and if they - how) moment of creation of EJB's instance.
For my understanding: if I have, #EJB annotated field, object of proper class is injected there. If such EJB is stateless, container simply take free instance from the pool of pre-created instances. Pool can be resized if necessary. It is stateless, because object isn't guaranteed to be preserved across method calls of our class (i.e. class which has field containing reference to EJB).
We can also use stateful EJB and in that case one instance is preserved during method calls. As I think, it will be simply injected once per object creation. (There is also singleton EJB, which is shared between all objects).
I can't find the purpose of #Scoped annotations for EJB here.
Edit 2:
One can use such combination of annotations if class is to be injected via EJB and DI (by #Inject) mechanisms. This is rather, however, special case and not elegant. I am asking if you know any other reasons.
Edit 3:
Please see my comment under arjan's answer.

A #Stateless or #Singleton bean may be explicitly scoped to prevent its scope being automatically modified to a scope that may be illegal. E.g. both these bean types are not allowed to be #RequestScoped. See this link for some more info: http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html/CDI.html
#Stateful makes a lot of sense to be (explicitly) scoped. Namely, without a scope you as a programmer have to take care to call the #Remove annotated method. This can be troublesome to guarantee, since such a bean is typically not used in a single method where you can call the #Remove method in a finally block. With a scope, the bean is exactly removed when the scope ends.
Furthermore, without a scope you can't always use injection to obtain a reference to a stateful bean's stub. Namely, every time the injection happens, you'll get a new instance. This is particularly troublesome when injecting a stateful bean in a request scoped (JSF) backing bean, where you have the intent to preserve the stateful bean across a couple of requests.
Then, in combination with #Named, you can also use a session bean directly as a backing bean to flatten your application layers (see e.g. http://jaxenter.com/java-ee-6-overview-35987-2.html). Obviously you want an explicit scope in that case. Now flattening your layers may not be a best practice in larger applications, but for smaller applications and/or people just beginning with Java EE there is definitely a wish to put business logic directly into the backing bean. It's then required that backing beans have access to the same kind of services (mainly transactions) that 'business beans' normally have.
Finally, Gavin King (CDI spec lead) has suggested to always use #Inject instead of #EJB. The only exception concerns remote EJBs, where #EJB is still used.
Part of the confusion around EJB and CDI is that CDI is a new component model in Java EE and still relatively new. Although they integrate fairly well with each other, they are still two different component models and not all best practices have been thought out yet. Reza Rahman (EG member, EJB book writer, and author of CDI implementation CanDI) has suggested that the EJB model could possibly be retrofitted in the future as a set of CDI services. Indeed, in Java EE 7 a step is being made by separating the transactional services from EJB and making them available via (CDI) annotations.

Related

How much overhead does prototype scope cause?

My understanding is that a prototype-scoped Java bean class is instantiated every time it is requested, as opposed to singleton-scoped Java beans which are instantiated once when the application starts up.
My question is: how much overhead does using the prototype scope cause?
Does the Spring framework make any attempt to recycle prototype-scoped objects to reduce the overhead caused by repeated instantiation?
Is the overhead caused by prototype scoping enough to warrant efforts to make as many of my Java bean classes stateless so that I can apply singleton scope to them?
You should not think of overhead between the prototype and singleton scope, but only the way they are used. If they are stateless objects that will live throughout the life time of the application, the correct scope is singleton. Many beans exist in that scope, for example controllers, beans in a service or persistence layer. Most beans related to Spring Security framework are also stateless and live in singleton scope.
If you want to create a brand new bean for a specific processing and then discard it when it has been used, then it is a use case for the prototype scope. As I mainly used spring for Web application I seldom used prototype scoped beans, but used request scoped beans which have a close use case: they are created for a HTTP request processing. The only point of attention is that if you have to inject a prototype or request scoped bean in a singleton bean, you will have to use a proxy that allows to connect to the current prototype bean (may be in thread storage) and not a bean that would have been created when the singleton was.
Using prototype scope is the same as if you were to instantiate using 'new' except that the new object will be managed by Spring. Spring will be able to apply aspects, inject dependencies, etc.. There will also be the overhead of the proxy class created to wrap the object.
Spring will not attempt to reuse the instances.
If you do not want to create a new instance whenever you reference the bean then you should not be using a prototype. Your solution will either require independent instances, maybe due to concurrency, or it will allow for a singleton. It is unlikely that the memory used by the object will be the deciding factor for what scope you use.

In spring, is there a performance difference between prototype and singleton? [duplicate]

This question already has answers here:
What is difference between singleton and prototype bean?
(9 answers)
Closed 3 years ago.
When I using spring framework to write business code, I always use the singleton scope and avoid using the prototype scope. I think there is a performance difference between prototype and singleton. Because of the prototype scope, spring creates a new instance every call. And I think it is slower than using the singleton scope. Am I right? And am I giving too many considerations to the performance?
I can relate to the question, I have been researching it recently. Construction of objects is very cheap, unless they actually do some heavy lifting in the constructor. You never think twice about constructing a bunch of lambdas in one statement. That's not the problem.
The problem is Spring's inefficiency, the way it wasn't architectured right. I have recently benchmarked Spring vs Guice. Singletons are slightly faster with Spring, but Prototypes are 20 times slower.
From code sanity point of view, you should always prefer Prototypes. Guice defaults to prototypes. javax.inject.Inject documentation defaults to prototypes. Spring lists some vague historical reasons and does Singletons.
Prototypes are safer because they cannot accidentally store state and use it in the wrong context. They cannot store "userId" from one request and use it in another, since with Prototypes, a brand new instance with clean state gets created every time. That's how I learned this pattern: we cached the wrong user context accidentally when using Singletons with RequestScoped Providers. Ouch. That mistake is important to avoid. Getting CPU is a much smaller problem.
To summarize: use Prototypes for better code, and dont use Spring if performance is very important.
Yes, you are right prototype scoped beans consumes more resources. According to the documentation:
The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.
The constructor is called at each request instead of only once for a singleton scoped bean. But there is another aspect to take into account. The documentation says:
Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the Java new operator. All lifecycle management past that point must be handled by the client.
If you want to avoid an out of memory exception, you have to take care yourself of the release of all resources (such as database connections) hold by the prototype scoped beans.
Unless it's really needed, it's better to use singleton scoped beans.
I don't think you'll see any noticeable performance difference between prototypes and singletons in general in the most basic sense.
It's true that there is only one singleton bean instance in the application context, and instances of beans defined with "prototype" scope are created for every request to that bean, however, we're talking about the performance of new object creation and its very cheap these days and optimized for non-expensive objects.
However here are some caveats:
What if the Constructor of the bean calls some pretty expensive code, its not spring's fault of course, because the programmer wrote the code this way, but still, actually, some pretty expensive code will be called every time the bean is created and it can drain the performance.
Slightly more interesting: we usually don't place code like this in consturctor, instead we use "lifecyle" methods like #PostConstruct / #PreDestroy.
For Singletons spring will call the post-construct method once when it creates a singleton and after that will place the bean onto the application context.
When the application context gets closes (usually when the app shuts down) the pre-destroy method is called to free up the resources, etc.
However, with Prototype scoped beans it's not the case:
Spring creates them upon every request to the bean, then calls the post-construct method, again for every single instance of the bean it creates, then doesn't store the instance in the application context. This means that spring doesn't call at all pre-destroy methods (because it doesn't have a clue who are these objects, it doesn't really manage them after they're created).
So this can (again, not spring's fault) lead to serious performance differences between the two.
If we'll take it further, sometimes spring has to wrap the object into some sort of proxy. These proxies are usually done with java.lang.Proxy in case of interfaces or with Cglib which is based on inheritance. Now this fact alone, when we're talking about wrapping prototype-scoped beans into proxy, can become a source of the serious difference in performance because Proxies are generated in runtime and Wrapping an Object with proxy (especially with CGlib) is pretty expensive.

what are proxing rules in CDI for beans when they have interceptor or decorator?

I ran 2 examples in weblogic ( I used a bean with dependent scope):
1)the bean has not any interceptors or decorators: the bean was not proxied
2)the bean has a interceptors : the bean was proxied
I think that there are two types of proxies in CDI:
1)client proxy: This proxy overrides all the non-private methods of the bean class, when these overridden methods are invoked the proxy looks up the correct instance( or proxy of second type) of the bean and then forwards the invocation onto the actual bean instance (based on this link). for dependent scope this proxy is not created
2)there is another proxy for applying interceptors and decorators and it is created when the bean has decorator or interceptors
Is my assumption about second type of proxy correct? Does the specification say anything about it?
You made a nice investigation indeed and you are right for the most part.
Here are the details.
Proxy
Normal scoped beans (#ApplicationScoped, RequestScoped,...) are indeed proxied, you don't get hold of the actual instance and what you are getting is a client proxy.
With #Dependent which is not normal scoped, you basically want to inject new instance every time so there is no need to have it proxied.
The above has some mentions in CDI spec, albeit not precise to give implementation space in which they can manipulate - users should't really care if they have a proxy or not for calling their methods works just fine.
Interceptors and Decorators
Moving on to interceptors - spec says nothing about this from what I know and leaves implementations to choose freely what to do with it. Following details are Weld-specific although from what I recall, OWB has it similar. There aren't really many option how to achieve it anyway.
For every interceptor/decorator, there is a "proxy" created, in fact a subclass, which allows to make interception/decoration happen. This subclass replaces the original bean and all calls go through it (e.g. it is in the underlying bean store instead of the original instance).
Again, from user perspective, this makes no difference and you shouldn't be worried about it.
Extra tooling for proxies/sublasses
Sometimes, very rarely, and most likely only when you are developing a CDI library, you may truly need to see if the injected bean is a client proxy or a subclass.
Weld offers tools for that, every bean which has a client proxy is implementing WeldClientProxy interface from Weld API. This interface allows you to grab the actual instance and some metadata.
Likewise, every intercepted and decorated bean is implementing WeldContruct as a marker interface.

Is it permitted to use #Stateful and #javax.faces.view.ViewScoped together?

My understanding is that
#Stateful
#ConversationScoped
is allowed, and is normal usage.
With the new JSF 2.2 ViewScoped (javax.faces.view.ViewScoped) annotation, which is documented to be fully compatible with CDI scope annotations, does this mean that:
#Stateful
#ViewScoped
Is a viable combination?
#Stateful is an EJB annotation, so technically your bean will be a stateful EJB bean, not a CDI bean. And it will only work in a full-blown application server.
In case of (only) JSF 2.2 + CDI use:
#javax.inject.Named // to expose a bean in the EL context
#javax.faces.view.ViewScoped // to make it view scoped
Also don't mix up the latter annotation with #javax.faces.bean.ViewScoped, it once took me a while to find the issue.
There's a nice example.
keep in mind that with #stateful, every time you inject it you will get a new concrete instance, because you're indicating storing state with that annotation. also the EJB layer concept of session is not the same as the JSF layer concept of session, and confusing the two can create all sorts of issues for you.
JSF session is tied to a specific client maintained by either a cookie or url-rewriting (container configuration).
EJB session is tied to a specific method execution (#Stateless) or a concrete instance (#Stateful).
unless you need to have durable serialization and state maintenance within the EJB, stateful is not going to give you want you want. you're best bet will be to separate the transactional aspects into a #Stateless and store your state in a #ViewScoped that gets passed into the #Stateless methods.

what is meant by context in CDI?

I am new to CDI. While reading, I am always encountering contextual objects, non contextual objects. What does they mean?
For example the below link
http://docs.jboss.org/weld/reference/latest/en-US/html/beanscdi.html#d0e881
Message-driven and entity beans are by nature non-contextual objects
and may not be injected into other objects
The context of a CDI framework is basically a big map of objects*. You can add objects to the context or make the CDI framework create objects from your service classes by using any CDI configuration method (spring xml beans/annotations like #Component/#Service).
Once you have the context you can get objects from it: (Spring: getBean(name))
Now you can configure dependencies between the objects/beans in the context, and the CDI will make sure any object you get from the context will have its dependencies set. This is the dependency injection part.
Non-contextual objects are simply not added to the context and the CDI framework does not know about them. Usually only service classes are part of the CDI context.
* Not really a map though, objects can be accessed by name, by type and other ways. The default is you get the same object each time you ask by the same name (singleton), although you may configure the CDI to create a new object each time you ask (prototype).
A context in CDI is some span during execution of your program when contextual objects can be used.
It defines when CDI container creates, destroys and how it links instances of those objects together.
Non-contextual objects are those that are not tied to any CDI context.
MDBs are one example, they are managed by EJB container and not intended to be used as ordinary objects.
Entities come and go as you interact with a DB via JPA, so they also cannot be tied to a context.
Another example is any object whose instances you create manually.

Categories