使用基于Enum的Singleton来缓存大对象(Java) [英] On using Enum based Singleton to cache large objects (Java)

查看:393
本文介绍了使用基于Enum的Singleton来缓存大对象(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来缓存一些非常大的对象,只能创建一次,因此需要被缓存?目前,我有以下内容:

  public enum LargeObjectCache {
INSTANCE;

private Map< String,LargeObject> map = new HashMap< ...>();

public LargeObject get(String s){
if(!map.containsKey(s)){
map.put(s,new LargeObject(s));
}
return map.get(s);
}
}

有几个类可以使用LargeObjects,是为什么我决定使用单例缓存,而不是将LargeObjects传递给使用它的每个类。



此外,地图不包含许多键或者两个,但是关键在程序的不同运行中可以有所不同)所以,在这种情况下,还有另一个更有效的地图吗?

解决方案

您可能需要线程安全,以确保您没有两个同名的实例。
对于小地图来说,这很重要,但是您可以避免一个可以使其更快的调用。

  public LargeObject get (String s){
synchronized(map){
LargeObject ret = map.get(s);
if(ret == null)
map.put(s,ret = new LargeObject(s));
return ret;
}
}


Is there any better way to cache up some very large objects, that can only be created once, and therefore need to be cached ? Currently, I have the following:

public enum LargeObjectCache {  
    INSTANCE; 

    private Map<String, LargeObject> map = new HashMap<...>();

    public LargeObject get(String s) {  
        if (!map.containsKey(s)) {
            map.put(s, new LargeObject(s));
        }
        return map.get(s);
    }
}  

There are several classes that can use the LargeObjects, which is why I decided to use a singleton for the cache, instead of passing LargeObjects to every class that uses it.

Also, the map doesn't contain many keys (one or two, but the key can vary in different runs of the program) so, is there another, more efficient map to use in this case ?

解决方案

You may need thread-safety to ensure you don't have two instance of the same name. It does matter much for small maps but you can avoid one call which can make it faster.

public LargeObject get(String s) {  
    synchronized(map) {
        LargeObject ret = map.get(s);
        if (ret == null) 
            map.put(s, ret = new LargeObject(s));
        return ret;
    }
}

这篇关于使用基于Enum的Singleton来缓存大对象(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆