@gresing

Кеширует ли java состояние hashmap или других коллекций?

Если все кроме volatile полей может быть закешировано, то почему используя конструкцию, которую я скину дальше мы считаем, что она thread safe? Разве, storage.get(word) не может вернуть кешированное значение? Возможно, это описано в спеке JVM, но найти не удалось :(
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);
}
  • Вопрос задан
  • 251 просмотр
Решения вопроса 1
sergey-gornostaev
@sergey-gornostaev Куратор тега Java
Седой и строгий
Перед входом в блок синхронизации или синхронизированный метод потоки обнуляют свои кэши, а при выходе сбрасывают кэш в память.

Из 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.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы