0

I have a web service built with VRaptor that uses CDI (weld 2.1.2.Final). I need to parallelize some of the processing made by the server (statistical analysis of industrial alarms). I'm doing that using a ExecutorService and Callable instances, unfortunately I need one Request Scoped dependence inside my Threads. Because of that dependence I'm facing this error:

WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

Is there a way to link the Threads to the Request where they were created using CDI?

*I know that I shouldn't be opening threads in the server, but this is the currently most viable option

Jan Galinski
  • 11,768
  • 8
  • 54
  • 77
Rafael Teles
  • 2,708
  • 2
  • 16
  • 32

1 Answers1

1

Pass it as constructor argument of the callable.

public class YourTask implements Callable<String> {

    private YourData data;

    public YourTask(YourData data) {
        this.data = data;
    }

    @Override
    public String call() {
        // Just use data.
    }

}

@Inject
private YourRequestScopedBean bean;

public void submit() {
    YourTask task = new YourTask(bean.getData());
    // ...
}

Note: do not pass the bean itself as it's basically a proxy whose instance doesn't exist in other thread.

See also:


Unrelated to the concrete problem, manually managing threads in a Java EE container, even though when done via a properly programmed ExecutorService, is frowned upon. It indicates you aren't aware of possibilities of Java EE's EJB scheduling and timer APIs. You may find the examples in this answer useful: Is it safe to start a new thread in a JSF managed bean?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for your reply. I know that manually managing threads in a Java EE is frowned upon. But in this case I need (or there is another solution that I can't see), in the system I'm developing we may need to consult 20+ database that may contain millions of data (It's a industrial alarm analysis system), I have to parallelize the process. Maybe I should make a microservice and segrete part of the process from my server, but that solution is too far away and would consume too much time. – Rafael Teles Jan 17 '16 at 23:41
  • "Note: do not pass the bean itself as it's basically a proxy whose instance doesn't exist in other thread" I didn't know that (I still got a lot to learn), there is no way to pass the bean itself? And once again, thanks for your answer – Rafael Teles Jan 17 '16 at 23:43
  • I'm also controlling the number of threads one user can spawn, and the total number of threads that can spawn – Rafael Teles Jan 18 '16 at 12:05