Java Reference
In-Depth Information
Managing startup singletons
Startup singletons can be used to auto-run business logic on application startup and cache
data for the application. A singleton class marked with the startup annotation will be in-
stantiated during application deployment. It must be stressed that this is during application
deployment. Containers, such as GlassFish, will throw a java.lang .IllegalAc-
cessException if your bean tries to access a stateless/stateful session bean from the
@PostConstruct method. So other beans may not be available yet, but you'll have
access to JPA and can manipulate the database. If multiple startup beans are used, the
@DependsOn annotation should be used to control the startup sequence. Without the
@DependsOn annotation, there's no guarantee that the singleton will be instantiated—a
changing random order should be assumed. It's also important that you don't create circu-
lar dependencies of startup singletons.
Handling exceptions
Exceptions generated from a singleton bean are treated differently than exceptions from a
stateless or stateful session bean. An exception thrown from the PostConstruct meth-
od of a singleton causes the instance to be discarded. If the exception is thrown from the
PostConstruct method of a startup bean, the application server may choose not to de-
ploy the application. An exception thrown by a business method doesn't result in the bean
being discarded—the bean will be discarded only when the application terminates. What
this means is that your application logic should take this into account. Also, because a
singleton bean is in existence for the entire life of the application, you might have to take
care when dealing with external resources. If the application is left running for weeks, you
must take care to ensure that there's appropriate error handling and recovery code in place.
If the bean opens up a socket connection to another system, at some point that socket con-
nection will be closed—watch out for time-outs.
3.5. Asynchronous session beans
New to EJB 3.1 is support for asynchronous beans with the @Asynchronous annotation.
This isn't a new type of session bean but rather a new functionality that you can use with
stateless, stateful, and singleton session beans. This new functionality enables methods in-
voked by the client on methods contained in the business interface to be executed asyn-
chronously on a separate thread. Prior to this, the only avenue for parallelization in Java
EE was via MDBs. Using and coordinating activities between MDBs and stateless/stateful
Search WWH ::

Custom Search