Question about the effect of setFlushMode on an injected, container managed EntityManager - ejb

I am using EJB 3.1 and I have a Stateless Session Bean that I am injecting an EntityManager into. One of the EJB's methods calls entityManager.setFlushMode(FlushModeType.COMMIT).
Two questions:
1) I assume that affects all EJBs that are part of this transaction. So for example if this SSB calls another method on another EJB which uses the REQUIRED transaction attribute and that EJB also injects an EntityManager then that entityManager used by that method will also be in a COMMIT flush mode. Is that true or do you have to explicitly set the flush mode in the method being called even if it is in the same TX?
2) Will setting the flushMode on the entity manager affect any other entity managers for the same PU injected into other EJBs but used in different transactions? I would assume not.
Thnx.

Your assumptions are correct. Yes, setFlushMode on the injected EntityManager affects all EMs for the PU in the same transaction. No, it will not affect EMs in other transactions. See this answer: EJB 3.1 Transaction, EntityManager

Related

EJB without transaction

I am using EJB in order to take advantages of:
Concurrent (instead of creating 2 threads, I divided the work into 2
EJB beans).
Pooling (I use stateless EJB a lot and I love the idea that the pool
contains a specific number of bean). This way, I am not afraid of
running out of memory. Memory usage is more predictable).
Asynchronous processing (all I need is just an annotation).
Well, the problem is I am using it with MongoDB so I don't need any transaction. I can use #TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) and #TransactionAttribute(TransactionAttributeType.NEVER) annotations but... it means I must specify it everywhere?
Is there anyway to disable EJB transaction by default?
In an EJB 3.0 container, annotate your EJB (or EJB method) with:
#Stateless
#TransactionManagement(TransactionManagementType.BEAN)
#TransactionAttribute(value=TransactionAttributeType.NEVER)
public class YourBean
for BEAN management. For CONTAINER management instead:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
#TransactionAttribute(value=TransactionAttributeType.NEVER)
public class YourBean
The default value is managed by the container but if you dont specify nothing to do i think you solve your problem.
Or annotate all the Ejb to donĀ“t support transaction
#Stateless
#TransactionManagement(TransactionManagementType.NEVER)
public class YourBean
Remember that the ejb transactions are executed in a hierarchical way, ie if the first method being invoked does not support methods "children methods" are handled in the same way

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

circular ejb dependencies: what does the spec say?

I know from experience that injection of circular dependencies in EJB do work, at least in some application servers.
I've done it multiple times with self-injection (e.g. to get an EJB proxy for #TransactionAttribute, #RolesAllowed, #Asynchronous etc. to work).
I've done it with more complex graphs too (A->B->A etc.), which obviously work too.
I've done it at least in Glassfish 3/4, Weblogic, and JBoss 7.3. Maybe Weblogic, not sure.
Now, I've been trying to find some precise guarantee from the specification, without success. There are provisions for this in CDI, but I couldn't find any explanation on why it works for EJBs. Is there some indirect one, maybe?
I'm looking from some references from EJB specifications regarding this.
I don't believe the EJB specification explicitly disallows self-injection, which means it implicitly allows it since there is no reason for the bean's own interface to be different from the interface of some other EJB. In practice, self-injection can only work for stateless (and singleton in EJB 3.1) and not stateful since each lookup/injection of a stateful bean creates a new instance, which would result in infinite recusion. For stateful, you can inject SessionContext and use the getter methods to return a "self-proxy" rather than using injection. This technique also works for stateless/singleton, and it might be marginally faster than using injection (particularly if you cache the result in an instance field the same as injection) since the EJB container can probably return a self-proxy more directly than going through injection/JNDI.
The only additional authority I can give to this answer is that I was one of the primary developers/maintainers of the EJB container in WebSphere Application Server for 5 years. To add to your list of products, I know that self-injection also works in practice on WebSphere Application Server.

Is it enough to convert a POJO to an EJB session bean ...?

Is it enough to convert a POJO like Util class to an EJB session bean by putting an annotation (#Stateless or #Stateful) and using injected EntityManager in it?
Yes, #Stateless in enough. Your bean will then become an EJB bean.
The only other requirement is that you can't create such a bean with new. You have to inject it using #EJB in another managed bean (JSF managed bean, Servlet, etc). Or if you aren't yet in any kind of managed bean, you can bootstrap a bean using a JNDI lookup.
Also, EJBs indeed greatly reduce the boilerplate code of starting and committing transactions when working with JPA.
Well It is enough but still few things need to be taken Care,
1) Mark your Entity manager and other new variables to Transient if POJO is used to persist some object.
2) It is better not to do so, as If u need to make it as EJB better to Create Some New Class for it as it is suggested way to not to create complexity.

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

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.

Resources