karthik2146
karthik2146

Reputation: 21

Garbage collection of static variables Java - out of memory

We have an application where we totally cache huge volume of data. The cache is maintained as static maps.

Since the data is modified daily by some batch cycles, we refresh the cache after the data is modified. Refreshing cache is done by creating new objects and reference the static variable to these new objects. So each day new objects will be created and old objects are dereferenced.

But the problem is server heap memory keeps on increasing until one day it crashed without of memory exception.

I really doubt whether the dereferenced objects are garbage collected.

This is my class.

Class CacheService {
 public static Map<String,Article> articleCache = null;

 public docache(){
     private Map<String,Article> tempArticleCache= new HashMap<String,Article>();

      //Caching stuff
       //finally
        articleCache = tempArticleCache; // i hope defreferencing takes place here.
 }

}

The function docache() will be called daily to update the cache. Could anyone help me achieve caching without this problem.

Upvotes: 2

Views: 2652

Answers (2)

user1800059
user1800059

Reputation: 43

try to use java.util.WeakHashMap that are Maps. Entries in the WeakHashMap will be removed automatically when your object is no longer referenced elsewhere.

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34367

I am suspecting that old maps are still referenced somewhere. I would advice you to try below(not to create a new map every time but simple clear the existing one and repopulate it):

      public docache(){ 
           if(articleCache!= null){
                 //clear the elements of existing map
                 articleCache.clear();
           }else{
                 articleCache = new HashMap();
           }
           //do the map population
      }

If this also doesn't work then take a memory snapshot before crash and check which exact objects are consuming your heap. That will give a better idea about the issue.

Upvotes: 2

Related Questions