3 Replies Latest reply on Nov 15, 2011 2:27 PM by Randall Hauch

    How to get a JCR Session from a stateless bean?

    Jonathan Fields Novice

      Hi All,


      I am attempting to invoke JCR from a Message Driven Bean (MDB) that is receiving messages from JMS.


      Since the MDB is stateless, I am invoking ServerLoader.load(), RepositoryFactory.getRepository(),  and Repository.login() with each invocation. This seems  inefficient. How expensive is this? In general, what's the best way to obtain a Session from a stateless bean (SLSB or MDB), or is this the best way?




        • 1. Re: How to get a JCR Session from a stateless bean?
          Randall Hauch Master

          The cost of finding the Repository depends on the type of URL your using. If the URL contains a JNDI name, finding the repository will require a JNDI lookup (to find the engine or the Repository instance). If the URL contains a configuration file, then finding a repository will not use JNDI but will require two map lookups (one for the engine and one for the Repository). Either way, it's often worth it to share the Repository if you can. Plus, the JCR spec requires that the Repository instance is thread-safe, so it's certainly safe to share the instance.


          The Session is another story. With ModeShape 2.x you should create a new session for every request (or message, in your case), since sessions are not thread-safe and cannot be used concurrently by multiple threads. There is also some snapshotting done in the session's cache, so you probably won't want to keep them around too long without refreshing. The JCR spec even suggests that the normal pattern is to create a new Session for a small task. Doing so is usually far easier and not really very expensive (the largest cost will probably be authentication).


          BTW, ModeShape 3 Session instances will be thread-safe, so you'll be able to share Session instances for reading content. It still won't work to share Session instances for writing content, since that by definition requires the session's transient state. But we're also trying to make it even cheaper to create new Session instances, so always creating a new Session for every request should be fine.

          • 2. Re: How to get a JCR Session from a stateless bean?
            Jonathan Fields Novice

            Great, thanks for the info. Since I'm accessing the repository in JBoss, it's a JNDI URL. So it sounds like a singleton for the Repository is safe, and then get a new Session with each invocation of the MDB.