G
G
gresing2017-09-25 19:15:32
Java
gresing, 2017-09-25 19:15:32

Does java cache the state of hashmap or other collections?

If everything except volatile fields can be cached, then why using the construction that I will throw off further, we consider that it is thread safe? Can't storage.get(word) return the cached value? Perhaps this is described in the JVM spec, but could not be found :(

private HashMap<String, Integer> storage = new HashMap<>();

public synchronized void addWord(String word) {
        Integer integer = storage.get(word);
        if (integer == null) {
            storage.put(word, 1);
        } else {
            storage.put(word, integer + 1);
        }
        logger.info(storage);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-09-25
@gresing

Threads flush their caches before entering a synchronization block or synchronized method, and flush the cache to memory when they exit.
From JSR-133:

But there is more to synchronization than mutual exclusion. Synchronization ensures that memory writes by a thread before or during a synchronized block are made visible in a predictable manner to other threads which synchronize on the same monitor. After we exit a synchronized block, we release the monitor, which has the effect of flushing the cache to main memory, so that writes made by this thread can be visible to other threads. Before we can enter a synchronized block, we acquire the monitor, which has the effect of invalidating the local processor cache so that variables will be reloaded from main memory. We will then be able to see all of the writes made visible by the previous release.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question