在Java中缓存和重用不可变单例对象的最佳方式是什么? [英] What is the best way to cache and reuse immutable singleton objects in Java?

查看:137
本文介绍了在Java中缓存和重用不可变单例对象的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个类是不可变的,我想使它成为一个单独的每个不同的值都使用静态工厂模式。
目标是防止相同的对象创建多次(100+)次并优化equals方法。



我正在寻找最佳方法缓存并重用此类的以前的实例。
首先想到的是一个简单的hashmap,但是有其他选择吗?

解决方案

有两种情况:




  • 如果不同对象的数量很小并且是固定的,那么应该使用 enum


    • 它们不会超出声明的常量,并且 EnumMap 针对它进行了优化

    • <否则,您可以按照您的计划缓存不可变实例:


      • 如果这些值可以通过数字进行索引在一个连续的范围内,然后可以使用一个数组


        • 这就是例如 整数 在给定范围内为 valueOf


      • 否则,您可以使用某种 地图




    在使用模式中,您可以选择仅缓存最后一个 N 实例,而不是迄今为止创建的所有实例。这是用于例如 re.compile 在Python的正则表达式模块中。如果 N 足够小(例如5),那么使用线性搜索的简单数组也可以正常工作。



    对于<$ c基于$ c> Map 的解决方案,或许一个有用的实现是 java.util.LinkedHashMap ,它允许您在 @时执行类似LRU的策略覆盖 removeEldestEntry

    还有 LRUMap Apache Commons Collections 更直接地实施此政策。



    另见





    相关的问题




    I have a class representing a set of values that will be used as a key in maps.

    This class is immutable and I want to make it a singleton for every distinct set of values, using the static factory pattern. The goal is to prevent identical objects from being created many (100+) times and to optimize the equals method.

    I am looking for the best way to cache and reuse previous instances of this class. The first thing that pops to mind is a simple hashmap, but are there alternatives?

    解决方案

    There are two situations:

    • If the number of distinct objects is small and fixed, you should use an enum
      • They're not instantiatiable beyond the declared constants, and EnumMap is optimized for it
    • Otherwise, you can cache immutable instances as you planned:
      • If the values are indexable by numbers in a contiguous range, then an array can be used
        • This is how e.g. Integer cache instances in a given range for valueOf
      • Otherwise you can use some sort of Map

    Depending on the usage pattern, you may choose to only cache, say, the last N instances, instead of all instances created so far. This is the approach used in e.g. re.compile in Python's regular expression module. If N is small enough (e.g. 5), then a simple array with a linear search may also work just fine.

    For Map based solution, perhaps a useful implementation is java.util.LinkedHashMap, which allows you to enforce LRU-like policies if you @Override the removeEldestEntry.

    There is also LRUMap from Apache Commons Collections that implement this policy more directly.

    See also

    Related questions

    这篇关于在Java中缓存和重用不可变单例对象的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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