A new type of session bean that was introduced in Java EE 6 is the singleton session bean. A single instance of each singleton session bean exists in the application server.
Singleton session beans are useful to cache database data. Caching frequently-used data in a singleton session bean increases performance since it greatly minimizes trips to the database. The common pattern is to have a method in our bean decorated with the @PostConstruct annotation; in this method we retrieve the data we want to cache. Then we provide a setter method for the bean's clients to call. The following example illustrates this technique:
package net.ensode.javaeebook.singletonsession; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import net.ensode.javaeebook.entity.UsStates; @Singleton public class SingletonSessionBean implements SingletonSessionBeanRemote { @PersistenceContext private EntityManager entityManager; private List<UsStates> stateList; @PostConstruct public void init() { Query query = entityManager.createQuery( "Select us from UsStates us"); stateList = query.getResultList(); } @Override public List<UsStates> getStateList() { return stateList; } }
Since our bean is a singleton, all of its clients would access the same instance, avoiding having duplicate data in memory. Additionally, since it is a singleton, it is safe to have an instance variable, since all clients access the same instance of the bean.