- Available from EJB 3.1, Singleton Session Beans are business objects having a global shared state within a JVM.
- The @Singleton annotation is used to mark the class as Singleton Session Bean.
- They are instantiated once per application and exist for the lifecycle of the application.
- In cases where the container is distributed over many virtual machines, each application will have one bean instance of the Singleton for each JVM.
- It maintains its state between client invocations but that state is not required to survive container shutdown or crash.
- A Singleton session bean is intended to be shared and supports concurrent access by clients.
- Concurrent access to the one and only bean instance can be controlled by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC).
- CMC can be tuned using the @Lock annotation that designates whether a read lock or a write lock will be used for a method call.
- The container is responsible for deciding when to initialize a Singleton bean instance.
- Additionally, Singleton Session Beans can explicitly request to be instantiated when the EJB container starts up, using the @Startup annotation.
- A singleton session bean is never passivated.
- A singleton session bean can also implement a web service.
- The lifecycle callbacks for singleton session bean are the same as that for the stateless session bean (i.e.) methods annotated with @PostConstruct and @PreDestroy.
Examples
- Loading a global daily price list that will be the same for every user might be done with a singleton session bean, since this will prevent the application having to do the same query to a database over and over again.
- Application hit counter