Question

Is there a way to create a durable jcr session which is kept alive during the whole application lifecycle ? The background is that I want to use this session for a JCR EventListener which updates my view on any incoming event. Therefore this listener has to be always connected with a session I think.

Was it helpful?

Solution

Yes, you can indeed create a regular session, use it to register your event listeners, and keep it alive for as long as necessary.

In fact, the event listeners will only be notified of events while the session used to register the listener is still alive. Of course, that long-lived session may prevent the repository from shutting down, so always log out of your sessions when your application or service shuts down.

One common best practice is to have the listener do as little work as possible. Listeners are called asynchronously (meaning the repository doesn't wait to complete the changes until the listeners to complete), which means this is likely done on a separate thread and the listener might cause resource issues if it takes a long time to complete. So if the work is not trivial, get off the thread as quickly as possible by (for example) submitting work to a queue and processing the queue separately.

Another best practice is for listeners to not read or write content using the same Session that was used to register them. A JCR Session is not required to be thread safe, and most implementations do not implement concurrency. That means that they cannot be safely used by multiple threads, even if that entails only reading content. (Some implementations do guarantee that Sessions are thread safe, but it's probably better to avoid relying upon that trait unless you want or need to be locked into that implementation.)

In summary, if a listener needs to do any work, get off the calling thread and use a separate Session to read or update content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top