Does the JVM create background threads when updating a HashMap, such that a HashSet of its keys may be 'out of date' in a single threaded program?

java multithreading hashmap synchronization hashset

73 просмотра

1 ответ

140 Репутация автора

I have a HashSet which contains the keys of a HashMap, and update the contents of the HashMap, adding a new key in the process. After I've done this, I then want to use the HashSet of keys again, since I know that they kept up to date with the keys of the HashMap. I just want to make sure that this is all done by the same thread, and that there is no concurrency going on here that I might be unaware of, such that I tell the HashMap to add the new entry, and before it has updated I have used the HashSet information while it is out of date.

In code:

HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
HashSet<String> myHashSet = myHashMap.keySet();

... processing ...

myHashMap.put(new_key, value);

... use the **original** HashSet of keys, myHashSet ...

Could the above situation occur, given that this is the only thread created by the programmer, such that myHashMap and myHashSet would be out of sync? I'm not talking about the programmer creating more than one thread - the main program runs in a single thread (see above).

Автор: Lord Cat Источник Размещён: 18.07.2016 05:25

Ответы (1)

2 плюса

17924 Репутация автора


No they won't because the key set is a view onto the actual keys in the HashMap.

From the Javadocs:

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

And you can see the same in OpenJDK's implementation of HashMap.

So for a single-threaded program these should always be in sync.

The Java collections classes don't do things with threads internally because it would make using them too difficult and error prone. They leave the threading model to the calling code and just provide guarantees (or otherwise) about which operations are thread-safe.

Автор: Paolo Размещён: 18.07.2016 06:00
Вопросы из категории :