I have a process which takes a long time to compute so it's marked as #Asynchronous in a Stateless EJB. When the process finishes, I'd like it to access a SessionScoped bean from the session which started the process to store the results.
Is that possible? How?
You could #Inject the needed EJB, but that probably won't work because you have no guarantee that session will still be available when your asynchronous method invocation finishes. You're probably going to have to find another solution if you want to use asynchronous methods.
Related
I have a Java EE app that's deployed on WildFly AS.
I have a method annotated with #Asynchronous and I need to set the max number of threads for this method.
I configured a new <managed-executor-service> in server config, but I don't know how to bind it to an async method.
This link: https://developer.jboss.org/message/851027#851027
provides a good answer to how (or when) to use #Asynchronous and when to use JSR-236 ExecutorService and concurrency utilities:
In short, #Asynchronous is a annotation (EE6) to mark an EJB method as async.
You can invoke the method and keep the future object to check whether the method is finished and get the result. The EJB Concurrency Utilities are provided to have a safe way in EE7 to delegate work to a parallel thread. Threads started by this ConcurrentUtilities are managed by the container.
In difference to a direct start of a Thread (which is not allowed for an EE application). There is less overhead than using #Async and you have a bit more control.
See also this link about how to inject a MES:
http://www.adam-bien.com/roller/abien/entry/injecting_an_executorservice_with_java
I have a singleton EJB(3.1) which is using default container managed concurrency and default (LockType.Write) for all methods, since its not specified explicitly.
I have an Asynchronous method which looks as below:
#Asynchronous
#TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
#AccessTimeout(-1)
public AsyncResult<Boolean> myAsyncMethod(....){
}
My question is, when invoked, will this method lock the whole singleton bean till the above method completes processing or will it lock only till the time the method returns the Future object to the client ?
Also what effect will "#AccessTimeout(-1)" the on the concurrency of this method/bean.
My question is, when invoked, will this method lock the whole
singleton bean till the above method completes processing or will it
lock only till the time the method returns the Future object to the
client ?
The singleton bean is never locked at all on the client thread. The client thread schedules the asynchronous method and returns a Future without accessing the bean. The thread that eventually executes the asynchronous method will lock the bean for the duration of the method execution.
Also what effect will "#AccessTimeout(-1)" the on the concurrency of
this method/bean.
The #AccessTimeout(-1) will cause the thread that eventually attempts to execute the asynchronous method to block until the container-managed lock can be acquired.
Answer to Q1: since the method is marked #Asynchronous, it will return immediately. No blocking what so ever
Answer to Q2: Using #AccessTimeout(-1) on a session bean method/class means that once a thread enters that method, it will block for ever until it completes processing. However, in this case its not a concern since the #Asynchronous will kick in, free up the calling thread and start the processing in a different background thread
Coincidentally, I happened to write a blog post on this topic couple of days back. I would also recommend reading up on the EJB 3.2 specification document - its a reliable and thorough reference material
I have a logging bean where I log how long database calls and bean method calls take via interceptors.
I have a bean that calls two #Asynchronous methods. Those two #Asynchronous methods call the database and are intercepted.
When the logging bean logs though, it appears that the database has taken 0 ms which can't be right. When I use this logging bean and all the interceptors without #Asynchronous calls everything works fine.
I'm using glassfish 3.1.2.2. The doc http://glassfish.java.net/nonav/docs/v3/api/javax/enterprise/context/RequestScoped.html says "The request context is destroyed: after the asynchronous observer notification completes," Does that mean that my logging bean instance in the #Asynchronous method is destroyed when the method completes? What can I use to accomplish my goal?
There are multiple layers:
A CDI proxy, which runs CDI interceptors and then calls the EJB.
An EJB proxy, which schedules async work and returns immediately.
EJB interceptors, which run on the async thread.
Presumably, you're using a CDI interceptor, which is measuring the time it takes for the EJB container to schedule the async work. If you switch to using an EJB interceptor instead (i.e., annotate the EJB method with #Interceptors), then you can measure the time taken to execute the work.
I am new to server side coding and JSP/servlets. I have a code which has 3 classes. 1st is a Serv class inherited from java httpservlet. In this i have doPost() method implemented. In doPost() i use object of the 2nd class ResourceClass. ResourceClass is a singleton class. Hence essentially to use any method is do something like ResourceClass.getInstance().readResource();
Now readResource furthur uses Java Native access library to read a resource from disk. Now my question is Since as i understand if 1000 clients connect to my server(Apache Tomcat) for each new request i will have a new servlet serving the request. But all these servlets will essentially use the same singleton object. Hence will this reading be thread safe.
I do not change any internal state. So i think it wont effect my output hence the whole stuff is Idempotent. But will all these requests be queued making the singleton class object a bottleneck. Or will each servlet has its own copy.
Also if i change the Resource state then in that case will it be thread safe.
First of all, you won't have a new servlet for each request. The same, unique instance of servlet will be used to concurrently handle all the requests. The servlet is also a singleton: the web container instantiates only one instance.
You say that the requests to your ResourceClass singleton will be queued. They won't, unless you mark the method as synchronized or use some other locking mechanism. If you don't, then the threads will invoke your singleton method concurrently.
Whether it's thread-safe or not is impossible to say without seeing the code of your singleton and the code of the JNI library. The fact that it's read-only is a sign that it could be thread-safe, but it's not guaranteed.
In a Java EE server, you only have 1 instance of each servlet.
On the other hand, each http request is processed by the server in its own thread.
There is one instance of ResourceClass because it's a singleton so you will have a bottleneck if the readResource() method is synchronized.
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.