Is it safe to inject an EJB into a servlet as an instance variable? - servlets

We all know that in the web tier there is the possibility that only a single instance of a given Servlet exists which services multiple requests. This can lead to threading issues in instance variables.
My question is, is it safe to inject an EJB using the #EJB annotation into a servlet as an instance variable?
My initial instinct would be no, under the assumption that the same instance of the EJB would service multiple requests at the same time. It would seem that this would also be the instinct of a number of other programmers: Don't inject to servlets
However have I jumped to the wrong conclusion. Clearly what is injected into the servlet is a proxy, under the hood does the container actually service each request with a different instance and maintain thread safety? As this forum would suggest: Do inject to servlets
There seems to be a lot of conflicting opinions. WHICH IS CORRECT???

It is safe to inject an EJB in a Servlet as a Servlet instance variable, as long as the EJB is Stateless. You MUST NEVER inject a Stateful Bean in a Servlet.
You must implement your EJB stateless in that it doesn't hold any instance variable which itself holds a stateful value (like Persistence Context). If you need to use the persistence context, then you must get an instance of it IN the methods of the EJB. You can do that by having a PersistenceContextFactory as a EJB instance Variable and then you get an instance of the entity manager from the Factory in the method of the EJB.
The PersistenceContextFactory is thread-safe, thus it can be injected in an instance variable.
As long as you comply to the above mentioned rules, it should be thread-safe to inject a Stateless Bean in a Servlet

Your reference "Don't inject to servlets" mentions nothing about ejbs or #ejb annotation. It talks about not thread safe objects such as PersistenceContext.
Per EJB spec you can access ejbs from variety of remote clients including servlets (EJB 3.0 Specification (JSR-220) - Section 3.1). Injecting ejb using #EJB annotation is a method of obtaining EJB interface via dependency injection (section 3.4.1) which is alternative to looking up ejb objects in the JNDI namespace. So there is nothing special about #EJB annotation with respect to EJBs obtained.
So, based on EJB 3.0 Spec, it's a standard practice to obtain ejbs from servlets using #EJB annotation.

It's a mixed bag.
Stateless session beans may be injected and are safe. This is because even if a single instance of a stub is used, access to the methods will be serialized by the container.
I think what inferreddesign says is not true. It doesn't matter if the stateless session bean uses a persistence context. Only one caller will ever access a single bean instance at the same time, so even though the persistence context is not thread safe, the EJB guards against multiple access to it. Think of it as if every session bean method has the synchronized keyword applied to it.
The main problem with injecting an EJB in a Servlet I think is performance. The single stub instance will become a major area of contention when multiple requests are queuing up while waiting for a session bean method to be executed for them.

I think the simple answer is that you aren't guaranteed that it is safe.
The reason for this is that there is nothing explicit in the EJB specification that says EJB home interfaces have to be thread safe. The spec outlines the behaviour of the server side part only. What you will probably find is that the client skeletons are actually thread safe but you would need to look at how they are implemented by the library you are using. The annotation part will just expand into a service locator so that doesn't buy you anything.

Related

How #EJB annotation is processed in EJB container 3.x from the moment when we deploy ejb components?

Questions about ejb session bean behavior when used as injected bean instances.
I'm not 100% sure how this works. I guess it from practice and from reading documents on the subject.
I want to know how #EJB annotation is processed by container in detail.
Session bean have interfaces, impl class, deployment descriptor. We package them in ejb jar.
What is putted in global JNDI by container? Static references to
business interfaces ?
How and when global JNDI is read from ?
When component JNDI ENC is populated with ejb reference ?
Is this reference in JNDI ENC (java:comp/env/beanB) is reference to
session bean component interface, session bean instance proxy or
session bean instance ? Is there difference for SLSB and SFSB ?
With #EJB annotation on field does every new ejb session bean
instance get new instance of injected ejb in the annotated field or
all ejb instances share the same injected ejb session bean instance
?
Does ejb injection by lookup (on session context) provide always new
injected ejb instance, example: calling ctx.lookup(ejbReference) in
loop ?
In EJB 3.0, the JNDI names are vendor-specific (if available at all; in theory, a container could support EJB references only), but vendors typically return an EJB reference/proxy. In EJB 3.1, the specification requires the EJB container to make specific java:global, java:app, and java:module names available, and the object returned from these lookups must be an EJB reference/proxy.
The global JNDI is accessed when you perform a JNDI lookup. The container might access the global JNDI names in other cases (e.g., when resolving #EJB(lookup="java:app/...")).
It's undefined when the container populates java:, but the contents must be available before lifecycle callback or business methods are invoked on the component instance.
#EJB/<ejb-ref>/<ejb-local-ref> ensure lookups always return an EJB reference/proxy and never an actual bean instance. The proxy ensures that all container services are performed (security, transaction, remoting, etc.) before invoking an actual bean instance. For SLSB, an arbitrary bean instance will be invoked, and the same or different actual instance might be invoked depending on the thread, concurrency, timing, vendor-specific configuration, etc. For SFSB, a bean instance with a specific identity will be invoked; you are likely to get the same bean instance, but you might not if the EJB container has passivated the actual bean instance, but reactivation should result in an instance with equivalent state. For singleton session bean in EJB 3.1, you are guaranteed the singleton bean instance will be invoked.
It's undefined whether you get the same proxy instance. For SLSB and singleton beans, injection or lookup could return a single proxy that delegates to the actual bean instance as mentioned above. For SFSB, the proxy is basically required to be a separate instance per injection or lookup since the proxy must store some state with the identity so it can invoke the specific actual bean instance.
It's undefined what the container does, but injection is typically implemented by containers using Context.lookup followed by Field.set (or Method.invoke for setter method injection). Regardless, the instance handling is as described above.

EJB & safe publication

I have been reading lately about safe publication of Java objects (e.g. here: http://shipilev.net/blog/2014/safe-public-construction/).
Until now I was trusting EJB container without questions when relying on container managed concurrency.
Now I'm wondering
1) how an EJB container can make sure that the EJB itself is published safely?
2) how an EJB container can make sure that objects created by its EJBs are published safely (e.g. EJB instance vars)?
E.g. stateless session bean can be accessed by different threads over time (I'm not necesseraly saying simultaneously), so unsafe publication is a potential issue.
For 1), I roughly see possibilities, e.g. by wrapping the EJB and using some volatile accesses to garantuee total order.
For 2), I don't see how EJB container can enforce it.
Maybe it is forbidden by the EJB 3.1 spec to keep instance variables in the EJB if it can be accessed by different threads?
Maybe the statement "don't worry about concurrency in container managed EJB" is not true, and I should use safe publication patterns (including volatile and/or final keywords) in the class definitions of the classes used in my EJB instance vars?
I'm surpirsed I missed this fundamental problemacy for that many years as a Java developer.
Regards,
Lars
If an EJB container is reusing instances, it must store them in a thread-safe object pool, which must use some synchronization (synchronized, compare-and-swap, etc.), which will ensure that everything written by the first thread will "happen-before" everything that happens on the second thread. EJB developers do not need to worry about synchronization (unless they're using singleton session beans with bean-managed concurrency or the EJB is going outside the scope of the EJB spec by storing data in static variables).

EJB 2.0 and 3.0 life cycle

Respected EJB Expert,
I am writing this email after lot of R&D. Recently I attended an interview wherea I was asked for EJB event cycle in terms of method invocation. I told them exactly whatever is mentioned at internet. But the interviewer was very dangerously expert. He asked me which component calls which method. Eg. who created the EJB home object and EJB Object.. I answered him with the info what I had... but then he confused me a lot especially by asking me who invokes the above methods in EJB 3.0. Basically he wanted me to tell the complete cycle starting from the client's JNDI lookup till client getting the response of the EJB method. He also wanted to know the enviornment in which the method or event occurs and who invokes the method or event.
I will be very thankful to you if can provide me with your inputs in the below format for all EJBs for 2.0 and 3.0 version
Environment ## Method-name or Event ## Method or Event Invoker
The correct answer is that the EJB container itself is responsible for creating the EJB home implementation, instantiating the EJB object instances, and invoking all lifecycle methods on the EJB object instance.
For EJB 2.x, the client looks up a reference to a home from JNDI, and the container provides an object that implements the home interface. The container home object responds to the create method by returning another container proxy object that implements the component interface, which allows it to implement all the EJB qualities of service (transaction, security, java:comp, etc.) before delegating the actual bean instance that it creates.
For EJB 3.x, the situation is similar, except the container proxy object that implements the business interface is either injected directly or looked up directly from JNDI because the home interface is no longer required.

Is the following request-scoped injection thread-safe?

#WebListener
public class AllRequestsWebListener implements ServletRequestListener {
#Inject HttpRequestProducer producer;
public void requestInitialized(ServletRequestEvent sre) {
producer.requestInitialized(sre);
}
}
...
#RequestScoped
public class HttpRequestProducer {
...
}
I don't know howto inject request-bean as method-parameter and therefore I can guess that it will work properly when Request-bean injection is threadLocal. Can someone explain me how it's implemented in a thread-safe manner?
What you have injected in your bean is a proxy representing the real deal. The proxy will always forward the invocation to the correct bean
Intuition based answer
I believe it is thread safe, as request scope is thread safe (session and above are not, as a user can open multiple browser sessions and use the same session ID)
I tested it, although it's empiric evidence, but the injected HttpRequestProducer gets a new instance each request.
Note that the requestInitialized and requestDestroyed can be (and in practice are) different threads, so I will investigate further if you intend to use the same injected object on both methods.
Specs backed answer
The hard part was to find hard evidence for this claim in the specs.
I looked into the CDI spec and couldn't quickly find conclusive evidence that a #RequestScoped object is thread safe (e.g. using thread local) however I assume that a #RequestScoped bean is using the same scope as the scoped beans in Java EE 5: (see here)
In there this clause is interesting:
Controlling Concurrent Access to Shared Resources In a multithreaded
server, it is possible for shared resources to be accessed
concurrently. In addition to scope object attributes, shared resources
include in-memory data (such as instance or class variables) and
external objects such as files, database connections, and network
connections.
Concurrent access can arise in several situations:
Multiple web components accessing objects stored in the web context.
Multiple web components accessing objects stored in a session.
Multiple threads within a web component accessing instance variables.
A web container will typically create a thread to handle each request.
If you want to ensure that a servlet instance handles only one request
at a time, a servlet can implement the SingleThreadModel interface. If
a servlet implements this interface, you are guaranteed that no two
threads will execute concurrently in the servlet’s service method. A
web container can implement this guarantee by synchronizing access to
a single instance of the servlet, or by maintaining a pool of web
component instances and dispatching each new request to a free
instance. This interface does not prevent synchronization problems
that result from web components accessing shared resources such as
static class variables or external objects. In addition, the Servlet
2.4 specification deprecates the SingleThreadModel interface.
So in theory, it seems that the object itself is going to have one instance per request thread, however I couldn't find any hard evidence that this is supported.

Why Servlets are not thread Safe? [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 6 years ago.
I need to know why the servlets are not thread safe ? And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?
I need to know why the servlets are not thread safe ?
Servlet instances are inherently not thread safe because of the multi threaded nature of the Java programming language in general. The Java Virtual Machine supports executing the same code by multiple threads. This is a great performance benefit on machines which have multiple processors. This also allows the same code to be executed by multiple concurrent users without blocking each other.
Imagine a server with 4 processors wherein a normal servlet can handle 1000 requests per second. If that servlet were threadsafe, then the web application would act like as if it runs on a server with 1 processor wherein the servlet can handle only 250 requests per second (okay, it's not exactly like that, but you got the idea).
If you encounter threadsafety issues when using servlets, then it is your fault, not Java's nor Servlet's fault. You'd need to fix the servlet code as such that request or session scoped data is never assigned as an instance variable of the servlet. For an in-depth explanation, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.
And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?
It is not thread safe. You're confusing the Struts dispatcher servlet filter with Struts actions. The struts actions are re-created on every single request. So every single request has its own instance of the request scoped Struts action. The Struts dispatcher servlet filter does not store them as its own instance variable. Instead, it stores it as an attribute of the HttpServletRequest.
Servlets are normal java classes and thus are NOT Thread Safe.
But that said, Java classes are Thread safe if you do not have instance variables. Only instance variables need to synchronize. (Instance variable are variables declared in the class and not in within its methods.
Variables declared in the methods are thread safe as each thread creates it own Program Stack and function variables are allocated in the stack. This means that variable in a methods are created for each thread, hence does not have any thread sync issues associated.
Method variables are thread-safe, class variables are not.
There is a single instance of a servlet per servlet mapping; all instance properties are shared between all requests. Access to those properties must take that in to account.
Struts 2 actions (not "controller servlet", they're neither servlets nor controllers) are instantiated per-request. Action properties will be accessed only by a single request's thread.
Servlets are normally multi-threaded.
Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The new thread is given an object reference to the requested servlet, which issues the response through the same thread. This is why it is important to design for concurrency when you write a servlet, because multiple requests may be handled by the same servlet instance.
The way that servlet containers handle servlet requests is implementation dependent; they may use a single servlet, they may use servlet pooling, it depends on the vendor's system architecture.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Servlet is not thread safe but we can make it as a thread safe by implementing that servlet class to SingleThreadModel
like the given below class definition but again the performance problem will be there so better option would be use synchronized portion
public class SurveyServlet extends HttpServlet
implements SingleThreadModel
{
servlet code here..
...
}
Servlet is not thread-safe by itself. You can make it thread-safe by making the service method synchronized.
you need to implement SingleThreadInterface to make it thread-safe.

Resources