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 (
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
annotations based on a read/write-lock model to provide declarative thread safety for
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.
Online Companion Information
Wiki article: http://community.jboss.org/docs/DOC-15569
Following is a full listing of all source code used in this runnable example.