sebastiandaschner blog
Simple and powerful cache in JavaEE
saturday, april 04, 2015An web/enterprise application always needs some kind of storage.
Mostly we use databases for that.
But for simple use cases with non-permanent data you don’t necessarily need a whole database.
The easiest form of key-value storage a Java developer could imagine would be the HashMap
.
In order to make a HashMap
“enterprisy” and accessible from the whole application it will reside in a Singleton Bean.
Furthermore the concurrency of the bean should be bean-managed to avoid unnecessary synchronisation.
Of course the map itself then has to be thread-safe.
A ConcurrentHashMap
is just perfect for this.
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class ModelCache {
private final Map<String, Model> models = new ConcurrentHashMap<>();
// get, getAll, store, remove ...
}
If the cache has to compute some data or execute some functionality on startup time the bean is also annotated with @Startup
to be sure that the data is there right at server startup time.
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class ModelCache {
// HashMap and access methods
@PostConstruct
public void preComputeNecessaryData() {
// ...
}
}
The storage/cache can now be injected in all other beans through the whole application.
@Stateless
public class ModelManager {
@Inject
ModelCache cache;
// ...
}
This scenario is simple and still powerful as long the stored data doesn’t need to be persistent beyond restarts and doesn’t need to be shared between several server instances. For these purposes JCache is a more powerful solution.
Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: