How to make cache thread-safe in your Java application
How to make cache thread-safe in your Java application
Leave feedback
On this page
This tutorial will explain how to make cache thread-safe by using synchronized block.
What method is thread safe?
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.
Non thread-safe code
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.
Making code thread-safe
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.