Search code examples
memory-managementgarbage-collectionweak-references

Creating strongreference from Weakreference


Following is a sample code of our application, where we are trying to keep a weak reference of a huge page model object, which takes a lot of memory.

Dictionary<int,WeakReference> modelCache;

IPageModel ReadPageModel()
{
   IPageModel page;
   if (!modelCache.ContainsKey(cacheKey) || !modelCache[cacheKey].IsAlive)
   {
      model = new PageModel();
      modelCache[cacheKey] = new WeakReference(Model);                
   }
   else
   {
      model = modelCache[cacheKey].Target as IPageModel;
   }
   return model;
}

The model that we are returning(in else part) is a reference to a weak object, so it can be null at later times.

Is there a way, so that we can create a strong reference to this object, and later when we are done with the object we can make it a weak reference.

I came across some examples where weak references are converted to strong but not vice versa.


Solution

  • Java gc weakreferenced objekts only when they are ONLY weakreferenced. Thus as long as you hold a normal reference to the object java will not gc it and you will not get a null reference.