3

I'm wondering what would be the most efficient (in terms of needed resources) scope for a repository class in CDI. Imagine the following scenario:

@RequestScoped
//OR @ApplicationScoped OR @SessionScoped OR @ConversationScoped?
public class SomeRepository{
  @Inject 
  private EntityManager em;

  public SomeClass getSomeClassById(int id){
    return em.createNamedQuery("getSomeClassById",SomeClass.class).
             setParameter("id",id).getSingleResult();
   }
}

The EntityManager in ths example is produced with a @RequestScoped scope.

user1727072
  • 309
  • 4
  • 14

1 Answers1

1

Interesting question I think. Unexpectedly I can't think of anything that makes these classes special. So I would make them @ApplicationScoped as a new instance would function exactly the same as the one I just discarded. Not sure it would have any noticeable impact on the heap, probably not but maybe if they had to be recreated a lot?

I think it's fine to go with what conceptually feels more right for you.

Karl Kildén
  • 2,415
  • 22
  • 34
  • But @ApplicationScoped means "only one instance per application" right? Would that cause this class to be a bottlneck if thousands of requests would be received at once? – user1727072 Mar 25 '13 at 09:32
  • 2
    @user1727072 no not at all. There's no concurrency management built into the scope. In this case it would also be thread safe since you inject only a proxy to the real entitymanager and each invocation will be forwarded to the correct instance. ApplicationScoped is the singleton pattern - everyone use the same instance possibly at the same time – Karl Kildén Mar 25 '13 at 21:41
  • iirc the @Singleton from EJB is threadsafe by default, perhaps this is what you are thinking of. – Karl Kildén Mar 25 '13 at 21:45