javamemory-managementjava-mememory-leaksmobile

Is this scenario suitable for WeakReferences?


I am working on querying the address book via J2ME and returning a custom Hashtable which I will call pimList. The keys in pimList {firstname, lastname} maps to an object (we'll call this object ContactInfo) holding (key, value) pairs e.g. work1 -> 44232454545, home1 -> 44876887787

Next I take firstName and add it into a tree. The nodes of the tree contains the characters from the firstName. e.g. "Tom" would create a tree with nodes:

"T"->"o"->"m"-> ContactInfo{ "work1" -> "44232454545", "home1" -> "44876887787" }

So the child of the last character m points to the same object instance in pimList. As I understand it, the purpose of WeakReferences is to that its pointer is weak and the object it points to can be easily GC'ed. In a memory constraint device like mobile phones, I would like to ensure I don't leak or waste memory. Thus, is it appropriate for me to make:

  1. pimList's values to be a WeakReference
  2. The child of node "m" to point to WeakReference

?


Solution

  • I am not sure if the WeakMap is the right thing here. If you do not hold strong references anywhere in your application, the data in the map will disappear nearly immediately, because nobody is referencing it.

    A weak map is a nice thing, if you want to find things again, that are still in use elsewhere and you only want to have one instance of it.

    But I might not get your data setup right... to be honest.