Search code examples
javajakarta-eeejbcdi

JavaEE - EJB/CDI Method Duration Mechanism


not sure how to title this issue but lets hope description may give better explaination. I am looking for a way to annotate a ejb method or cdi method with a custom annotation like " @Duration" or someothing aaand so to kill methods execution if takes too long after the given duration period. I guess some pseudo code will make everything clear:

public class myEJBorCdiBean {

@Duration(seconds = 5)
public List<Data> complexTask(..., ...)
{
  while(..)
  // this takes more time than the given 5 seconds so throw execption
}

To sum up, a method takes extremely long and it shall throw a given time duration expired error or something like that

Kinda a timeout mechanism, I dont know if there is already something like this, I am new to javaEE world.

Thanks in advance guys


Solution

  • You are not supposed to use Threading API inside EJB/CDI container. EJB spec clearly states that:

    The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.

    Managed beans and the invocation of their business methods have to be fully controlled by the container in order to avoid corruption of their state. Depending on your usecase, either offload this operation to a dedicated service(outside javaee), or you could come up with some semi-hacking solution using EJB @Singleton and Schedule - so that you could periodically check for some control flag. If you are running on Wildfly/JBoss, you could misuse the @TransactionTimeout annotation for this- as EJB methods are by default transaction aware, setting the timeout on Transaction will effective control the invocation timeout on the bean method. I am not sure, how it is supported on other applications servers.

    If async processing is an option, then EJB @Asynchronous could be of some help: see Asynchronous tutorial - Cancelling and asynchronous operation.

    As a general advice: Do not run long running ops in EJB/CDI. Every request will spawn a new thread, threads are limited resource and your app will be much harder to scale and maintain(long running op ~= state), what happens if your server crashes during method invocation, how would the use case work in clustered environment. Again it is hard to say, what is a better approach without understanding of your use case, but investigate java EE batch api, JMS with message driven beans or asynchronous processing with @Asynchronous