Appendix D. Singleton Session EJB: RSS Cache Example


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.

Source Listing

Following is a full listing of all source code used in this runnable example.

Implementation Resources ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.