Communicating between cdi session contexts — with database, will proper cdi context be invoked?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 21:57:49

I guess I have to answer my own question --

  1. Contexts are not propagated to new threads or asynchronous calls. This is an undefined behavior of the CDI 1.0 spec, and so containers are not required to keep track of which context created a thread. If you create a thread and then fire off a CDI event once the thread wakes up, that CDI event will have no active context, and will throw the following error: org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.RequestScoped or something specific to the scope your thread was trying to activate. See this Glassfish ticket, which really isn't a bug, it's just undefined behavior.

  2. Therefore, when any background polling thread is set up to check if there are any changes to a user's data, when the thread detects the change it has no way to communicate (via CDI events) with the user's session context. The thread has no context at that moment. This seems to be an unanswered question for a few people: on the jboss forum and the seam forum.

Hopefully my solution will help. Until CDI 1.1 defines a way to propagate session context to threads, you have to make the user poll for their own data, and when they get their new data, they can act on it within their own session context. I set up my own system to use the database to store an event queue for each user, and when they poll, they just iterate through their queued messages and fire them off as if they were CDI messages sent in their own session context.

If a weld CDI expert could correct me if I'm wrong, I would appreciate it!

I don't think the CDI event bus can be used to communicate between user sessions.

Wouldn't it be better to solve this problem with a JMS message broker? Your application will scale so much better! Run it as a separate instance or embed it in your application server. You could for example use an ActiveMQ broker.

Post a notification message on a JMS topic, and make user sessions subscribe to it. I haven't yet used the Seam 3 JMS module, but it looks like it is able to bridge the gap between JMS and CDI. Using Seam JMS you could receive JMS messages in each user session. The example in the documentation explains how for each user you register a JMS listener in the @PostConstruct of a @SessionScoped bean.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!