[guardian-dev] NetCipher: WeakSet Alternatives

Mark Murphy mmurphy at commonsware.com
Mon Apr 25 19:37:56 EDT 2016


In my work on tying NetCipher into various HTTP stacks, I wanted a
WeakSet: a collection where the values were held weakly. This is for
callback/listener interfaces, so if the party that registers a listener
fails to unregister, a singleton does not trigger a memory leak.

Unfortunately, the one WeakSet implementation that I found is buggy. :-(

The canonical solution for Java is to use Collections#newSetFromMap() on
a WeakHashMap. WeakHashMap holds the keys weakly; newSetFromMap()
creates a Set interface on top of the Map's keys. However,
newSetFromMap() was only added to Android with API Level 9.

Options:

1. Say "screw it" and use a regular HashSet, and if there's a memory
leak, it's the job of the developer using NetCipher to detect and
address it (since, in truth, they are screwing up).

2. Set NetCipher's minSdkVersion to 9, up from its current 8.

3. Just use WeakHashMap directly, only paying attention to the keys.
This will make the code a little funny looking, but it'll work.

4. See if I can find an Apache Harmony edition of Collections from which
we can get an Apache-licensed newSetFromMap() implementation. My guess
is that there is none, otherwise Android would have had this method from
API Level 1.

Thoughts?

-- 
Mark Murphy (a Commons Guy)
https://commonsware.com | https://github.com/commonsguy
https://commonsware.com/blog | https://twitter.com/commonsguy


More information about the guardian-dev mailing list