I would like to cache some IO with the help of ConcurrentHashMap. The modification on the binary file should be reflected in cache as well. Since the cache is going to be used by multiple threads all IO operations are synchronized. Modifications of map go inside the same synchronized block. Which roughly looks like:
synchronized (file) {
file.deleteRecord(index)
map.remove(index);
}
and
synchronized(file) {
file.writeRecord(index, record);
map.put(index, record);
}
Both map and file are private and are not seen from outside the cache-class.
Is thread-safety preserved if cache reads, namely map.get(index), go without the synchronized block?
As I mentioned earlier, ConcurrentHashMap is used as map implementation.
Yup. This is basically the point of
ConcurrentHashMap. From the documentation:and from the package documentation:
(Both of those documentation pages have much more detail, of course. They’re worth reading carefully.)