LOAD and CACHE application-scoped data with @Singleton and @Stateless

Well, I’ve made some tests, and I’ve also tried the @Decorator way. This still seems to be the best one.

@Entity bean and @Stateless bean are the same of the question, while I’ve changed the @Singleton bean as follows, also adding the classic timed cache:

@Singleton
public class RoomsCached {

    @Inject
    Rooms rooms;

    private List<Room> cachedRooms; 
    private long timeout = 86400000L; // reload once a day
    private long lastUpdate;    


    public List<Room> getCachedRooms() {
        initCache();
        return cachedRooms;
    }

    public void initCache() {
        if (cachedRooms == null || expired()) {
            cachedRooms = Collections.unmodifiableList(rooms.findAll());
            lastUpdate  = System.currentTimeMillis();
        }
    }        

    private boolean expired() { 
        return System.currentTimeMillis() > lastUpdate + timeout; 
    }

}

No need to @PostConstruct, nor to @EJB, no sync issues with the underlying, @inject-ed @Stateless bean.

It’s working great.

Leave a Comment