Using SoftReference for static data to prevent mem

2019-05-19 01:49发布

I have a class with a static member like this:

class C
{
  static Map m=new HashMap();
  {
    ... initialize the map with some values ...
  }
}

AFAIK, this would consume memory practically to the end of the program. I was wondering, if I could solve it with soft references, like this:

class C
{
  static volatile SoftReference<Map> m=null;
  static Map getM() {
    Map ret;
    if(m == null || (ret = m.get()) == null) {
      ret=new HashMap();
      ... initialize the map ...
      m=new SoftReference(ret);
    }
    return ret;
  }
}

The question is

  1. is this approach (and the implementation) right?
  2. if it is, does it pay off in real situations?

7条回答
家丑人穷心不美
2楼-- · 2019-05-19 02:43

This is okay if your access to getM is single threaded and it only acts as a cache. A better alternative is to have a fixed size cache as this provides a consistent benefit.

查看更多
登录 后发表回答