How to make cache thread-safe in your Java application

This tutorial will explain how to make cache thread-safe by using synchronized block.


We can say that a method is thread-safe when multiple threads can call it without breaking the functionality of this method. Achieving thread safety is a complex task and so general-purpose classes are usually not thread-safe. The most common way to achieve thread-safety is by locking the resource for the exclusive use by a single thread at any given point of the time.

The issue

We have a web-application where multiple users can simultaneously view the same file. The web-application uses GroupDocs.Viewer on the server-side and we want to make sure that multiple-threads can safely read from and write to the cache, in other words, make cache thread-safe.

The GroupDocs.Viewer enables users to use caching to improve the performance of the application when the same document is processed multiple times (read more about caching here.) The FileCache is a simple implementation of Cache interface that uses a local disk to store the cache files is available from the com.groupdocs.viewer.caching package. The FileCache is not thread-safe, so our task is to make it thread-safe.

The solution

The FileCache class uses a local disk to read and write output file copies, so we need to make reads and writes to disk thread-safe. The simplest way is using synchronized block. Let’s implement a class which will wrap around not thread-safe class which implements the Cache interface.

    class ThreadSafeCache implements Cache {
        private final Cache _cache;

        public ThreadSafeCache(Cache cache) {
            _cache = cache;

        public void set(String key, Object value) {
            synchronized (_cache) {
                _cache.set(key, value);

        public Object get(String key) {
            synchronized (_cache) {
                return _cache.get(key);

        public List<String> getKeys(String filter) {
            synchronized (_cache) {
                return _cache.getKeys(filter);


With synchronized statement we can write quite a simple code to achieve thread-safety in our applications as shown in this tutorial. 

More resources

GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured Java library we provide simple but powerful free Apps. You are welcome to view Word, PDF, Excel, PowerPoint documents with free to use online GroupDocs Viewer App.