开发者

Creating strongreference from Weakreference

开发者 https://www.devze.com 2023-04-06 10:35 出处:网络
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.

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) i开发者_JAVA技巧s 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.


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.


Thanks Xeno Lupus,

So the reference was strong reference, but before I put the value object got collected.. Now i have modified the code as follows,

   IPageModel page;
   if (modelCache.ContainsKey(cacheKey) && modelCache[cacheKey].IsAlive)
   {
      model = modelCache[cacheKey].Target as IPageModel;                         
   }
   if(model == null)
   {
      model = new PageModel();
      modelCache[cacheKey] = new WeakReference(Model); 
   }
   return model;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号