I can use WeakHashMap instead of HashMap

I went through WeakHashMapin Java. And what I understood WeakHashMapexactly matches HashMap, except that its key links are WeakReference. This means that links to keywords are entitled to gc, and when it is falsified, its record will be deleted from the card. This is impossible in HashMap. Please correct me if I am wrong.

I have one question.

Now in the future. If I get a requirement that I need to use the card to enter the key and value, can I continue with WeakHashMap? Or do I need to consider any scenario where WeakHashMapit will not match only HashMapwill match?

+4
source share
2 answers

You need to consider the context in order to decide if it is proper / safe to use WeakHashMap.

Here's an example where WeakHashMap will not work (pseudocode)

Map<Name, Details> map = ...
do for ever:
    name = get name from user
    if lookup:
        details = map.get(name)
        display details
    else if create:
        details = get details from user
        map.add(name, details)

Using WeakHashMap, there is a risk that the records will drop out of the table and the search for users will fail. There is no risk with HashMap.


There is also the problem that WeakReference and everything built on it are more expensive than regular links. They use more space and time. Moreover, the Reference classes incur overhead every time the GC encounters them, which can increase the GC pause time.

However, the run-time overhead problem should usually be secondary to the correctness problem.

  • HashMap, WeakHashMap, . .

  • WeakHashMap, HashMap, .

+2

, WeakHashMap HashMap, :

  • API, HashMap<K, V>, Map<K, V>.
  • , - . , WeakHashMap , . , , , , . (. JavaDoc.) WeakHashMap , . .
  • .

WeakHashMap , (, ), , , , .

+1

Source: https://habr.com/ru/post/1611052/


All Articles