I\'m looking for an elegant solutions to the old problem of loading and caching static, shared data at application startup (with an infinite lifetime). <
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.