开发者

Request scoped context for stateless session beans

Is there a request-scoped context for EJB3 session-beans? My environment is Java-EE-5.

This example

@Remote(SessionFacade.class) @Stateless
public class SessionFacadeBean implements SessionFacade {
  @EJB
  private Other bean;

  public void myBusinessMethod() {
     // TODO: get or create *myRequestScope*
     *myRequestScope*.put("demo", Integer.valueOf( 1 ));
     bean.otherBusinessMethod();
     sysout(*myRequestScope*.get("demo"));
  }
}

@Local(Other.class) @St开发者_如何转开发ateless
public class OtherBean implements Other {
  public void otherBusinessMethod() {
     // TODO: get or create *myRequestScope*
     *myRequestScope*.put("demo", Integer.valueOf( 2 ));
  }
}

should always printout "2" when invoking SessionFacadeBean#myBusinessMethod() - irrespective of parallel invocations.

I do not have the luxury of using CDI. And, it should also work independently of transaction propagation (so JCA is also not an option).


Stateless EJBs, are their name suggests do not store state, so there is no concept of request-scope. There is a session scope that is limited to the current runtime session context, where you cannot store state as well, so that rules out any option of storing state within the bean or within the container.

You might find some luck by using ThreadLocal variables, but this as the name suggests, is scoped to the current thread of execution. Going by your posted code, this appears to be what you would want. The problem with this approach is that,

  • Thread objects are simply not destroyed once the EJB method has completed execution; they are returned to the container's thread pool. Therefore, if you read the ThreadLocal value in a different context of execution, you will find the value of the previous execution context that used the same thread. In other words, ensure that your application always puts values in the ThreadLocal object before reading them.
  • Additionally, free any ThreadLocal objects once you do not require them, otherwise you would have a memory leak on your hands.


Is there a request-scoped context for stateless session-beans?

Short answer is No.

The long answer is: You need some context to share data between invocations of your business methods. This could be a design issue. Requestscope is a concept of web-tier.

  • In the Web-tier the request,page,session and application scope is implemented as a Hashmap. So you could pass a reference to a Hashmap as context to share all data.

  • Another approach could be to use a singleton (which needs to be shared between nodes e.g. using ehcache).

  • Migrate to EJB 3.1 and use @Singleton

  • Consider to use stateful Beans and put your request-scope into the beans session scope which could be removed after you leave the request scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜