Skip to content

Wrong usage of WeakHashMap in LookupFactory.java #276

@sundararajana

Description

@sundararajana

LookupFactory has the following field declaration:

private WeakHashMap<Class<?>, Lookup> lookups = new WeakHashMap<>();

From the javadoc of WeakHashMap:

"WeakHashMap is a Hash table based implementation of the Map interface, with weak keys. ...

Implementation Note:
The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded.
"

See also: WeakHashMap

MethodHandles.Lookup refers back to the underlying lookup Class by an instance field (strong reference):

$ javap -p java.lang.invoke.MethodHandles.Lookup | grep lookupClass
private final java.lang.Class lookupClass; public java.lang.Class lookupClass();
private java.lang.Class lookupClassOrNull(); private java.security.ProtectionDomain lookupClassProtectionDomain(); private static void checkUnprivilegedlookupClass(java.lang.Class);

=> lookups declaration in LookupFactory always leaks <Class, Lookup> pairs once created!

If you want to cache/associate a value for a every Class object, you can use java.lang.ClassValue. See also:

ClassValue

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions