• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on WeakHashMap  RSS feed

 
Edmund Yong
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what I read about the WeakHashMap class, WeakHashMap works exactly like HashMap, except that the keys are referred to using weak references. If a key becomes garbage, its entry is removed automatically. Consider the following codes:



My question: will the entry in the map in the thread get removed? Constant.SALUTATION is a static variable. Assuming that it is only used in the constructor call of SomeThread, is it strongly referenced in this case?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question: will the entry in the map in the thread get removed? Constant.SALUTATION is a static variable. Assuming that it is only used in the constructor call of SomeThread, is it strongly referenced in this case?


Not only is there the static variable, but it is a string literal as well (meaning you have a reference from the string pool). So, you have two strong references and one weak refeerence to the key.

Obviously, the key won't be GC'ed due to the strong references.

Henry
 
Edmund Yong
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry,

Suppose that I change the key below (line 12) so that it would not be strongly referenced elsewhere. In this way, can I say that the key in the map is now only weakly referenced?

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!