You need to perform the following steps to complete this recipe:
- Let's create a User class. This will be our cached object:
public class User {
private String name;
private String email;
//DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS
}
- Next, create a singleton that will hold our user list cache:
@Singleton
@Startup
public class UserCacheBean {
protected Queue<User> cache = null;
@PersistenceContext
private EntityManager em;
public UserCacheBean() {
}
protected void loadCache() {
List<User> list = em.createQuery("SELECT u FROM USER
as u").getResultList();
list.forEach((user) -> {
cache.add(user);
});
}
@Lock(LockType.READ)
public List<User> get() {
return cache.stream().collect(Collectors.toList());
}
@PostConstruct
protected void init() {
cache = new ConcurrentLinkedQueue<>();
loadCache();
}
}
Now, let's see how this recipe works.