Proper use of the Java Weak Reference for nested collections

I need to define a weak reference map whose value is Set. I use MapMaker for Google collections, for example:

Map<Class<? extends Object>, Set<Foo>> map = new MapMaker().weakKeys().weakValues().makeMap();

So, Set<Foo>can one use regular HashSet? Or I need to create a weak HashSet, for example:

Collections.newSetFromMap(new WeakHashMap<Foo, Boolean>());

And why?

Another question, my card key is class objects, when will the class object become inaccessible? In other words, what is the lifetime of a class object?

Thank.

Update: The first question is not entirely clear. My concern was that when I do map.get(key).add(foo)to add an instance of foo to Set, it will also add a strong reference to the instance of foo and thus prevent its GCed? That's why I was wondering if a weak HashSet should be used.

+3
1

, Class , Classloader . . 12.7 JLS:

, , . 12.6. , , .

WeakReference<Class>, , , ( 100% , ).

, - HashSet? , . , Map , Set , , HashMap. (Google- , , ). GC Set , Map .

, Foo; Set<Foo>, Foo . . Javadoc java.lang.ref:

, - . [...] , , , . , .

, ( Map) → (Map Set) → (Set Foo), Foo .

, , . , , , Foo ; Set<Foo>, Foo.

, , , . , , - Multimap - - MultimapMaker.weakValues(). MultimapMaker: . guava-libraries issue # 142 . !

+4

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


All Articles