CDI RequestScoped,Threading and the javax.enterprise.context.ContextNotActiveException

Accessing a CDI @RequestScoped bean:


import javax.enterprise.context.RequestScoped;

@RequestScoped
public class Greeter {
    
    public String hello(long number){
        return "hello, duke " + number;
    }
}

asynchronously:

import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
@ApplicationScoped
public class GreetingResource {
    
    @Inject
    Greeter greeter;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        var numbers  = Stream.generate(System::currentTimeMillis)
        .limit(10)
        .toList();
        return numbers.parallelStream() //stream() would work...
        .map(number -> this.greeter.hello(number))
        .collect(Collectors.joining(","));
    }
}

may cause a javax.enterprise.context.ContextNotActiveException, like e.g.

javax.enterprise.context.ContextNotActiveException: javax.enterprise.context.ContextNotActiveException: RequestScoped context was not active when trying to obtain a bean instance for a client proxy of CLASS bean [class=airhacks.Greeter, id=59c45f3d436e11499d8793e2c5fc0c26ffbe3933]
- you can activate the request context for a specific method using the @ActivateRequestContext interceptor binding

The entire example was implemented, and explained, "from scratch":

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments
License