Appendix D. Singleton Session EJB: RSS Cache Example

Description

Often we have a business process best modeled by a single instance instead of a backing pool (like SLSB) or cache (SFSB). New to EJB 3.1, the @Singleton EJB creates a sole backing instance to service all incoming requests.

This has two important consequences. First, if this instance is eagerly brought into service (via the @Startup) annotation, we may now have application lifecycle events (@PreConstruct / @PostConstruct).

Second, because all requests are sharing a single instance, for the first time EJB developers must address concurrency of writable, shared state. No SLSB or SFSB bean instance will ever be accessed by more than one thread at a time (thread safety via confinement). This is not the case with @Singleton, so the specification introduces container-managed concurrency annotations based on a read/write-lock model to provide declarative thread safety for developers.

Our example models a simple cache which hangs onto an RSS feed. Read operations will not block, but refreshing the cache will block all readers until complete. Assuming a much higher percentage of reads to refreshes, this cache will remain efficient.

Get Enterprise JavaBeans 3.1, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.