Java Reference
In-Depth Information
other bean. As already mentioned, singleton beans can be marked to start when the applic-
ation is deployed with the added semantics that application launch isn't complete until the
startup beans have successfully completed. Just like stateless and stateful beans, singleton
beans also support injection, security, and transaction management.
3.4.1. When to use singleton session beans
Prior to EJB 3.1 most developers of applications with a web front-end probably used a
“startup servlet” to fulfill the role of an EJB singleton bean. The servlet was configured to
eagerly start by the web container via settings in web.xml. The startup logic was placed in
the init method of the servlet. Common tasks such as configuring logging, initializing
database connections, and caching frequently accessed data in memory were implemented
here. Cached data was then placed in the application session scope of the web application
container. Special constructs were then necessary to synchronize updating of the cached
data, which could be especially tricky if the application was load-balanced across multiple
servers. This wasn't an optimal solution.
Singleton beans enable you to get around having to use custom solutions, such as startup
servlets, POJOs with static fields, and various other derivations. Thus, you use singleton
beans when you want to have a shared state that's application-global or a single chokepoint
for a specific task. Let's look at these in more detail, and also, more importantly, see when
you shouldn't use a singleton session bean.
Startup tasks
Very often when an application is deployed, you want to perform a couple of operations
before the application is accessible to external users and other systems. When the applic-
ation starts up, you may want to check the database for consistency or verify that an ex-
ternal system is up and running. Very often there are race conditions with startup pro-
cesses—although LDAP might be configured to start before GlassFish, GlassFish might
successfully deploy an application before LDAP is ready to accept connections. A
singleton bean marked annotated to launch on startup could repeatedly poll for LDAP and
thus ensure that the application isn't accessible until all of the external services are ready
to accept connections.
Search WWH ::

Custom Search