• Integer缓存池知道吗?


    因为根据实践发现大部分的数据操作都集中在值比较小的范围,因此Integer搞了个缓存池,默认范围是-128到127,可以根据通过设置JVM-XX: AutoBoxCacheMax = 来修改缓存的最大值,最小值改不了。

    实现的原理是int在自动装箱的时候会调用Integer.valueOf,进而用到了IntegerCache。

    1. @IntrinsicCandidate
    2. public static Integer valueOf(int i) {
    3. if (i >= IntegerCache.low && i <= IntegerCache.high)
    4. return IntegerCache.cache[i + (-IntegerCache.low)];
    5. return new Integer(i);
    6. }

    没什么花头,就是判断下值是否在范围之内,如果是的话去 IntegerCache 中取。

    IntegerCache在静态块中会初始化好缓存值。

    1. private static class IntegerCache {
    2. static final int low = -128;
    3. static final int high;
    4. static final Integer[] cache;
    5. static Integer[] archivedCache;
    6. static {
    7. // high value may be configured by property
    8. int h = 127;
    9. String integerCacheHighPropValue =
    10. VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    11. if (integerCacheHighPropValue != null) {
    12. try {
    13. h = Math.max(parseInt(integerCacheHighPropValue), 127);
    14. // Maximum array size is Integer.MAX_VALUE
    15. h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
    16. } catch( NumberFormatException nfe) {
    17. // If the property cannot be parsed into an int, ignore it.
    18. }
    19. }
    20. high = h;
    21. // Load IntegerCache.archivedCache from archive, if possible
    22. CDS.initializeFromArchive(IntegerCache.class);
    23. int size = (high - low) + 1;
    24. // Use the archived cache if it exists and is large enough
    25. if (archivedCache == null || size > archivedCache.length) {
    26. Integer[] c = new Integer[size];
    27. int j = low;
    28. for(int i = 0; i < c.length; i++) {
    29. c[i] = new Integer(j++);
    30. }
    31. archivedCache = c;
    32. }
    33. cache = archivedCache;
    34. // range [-128, 127] must be interned (JLS7 5.1.7)
    35. assert IntegerCache.high >= 127;
    36. }
    37. private IntegerCache() {}
    38. }

    所以这里还有个面试题,就是啥 Integer 127之内的相等,而超过127的就不等了,因为127之内的就是同一个对象,所以当然相等。

    不仅Integer有,Long 也是有的,不过范围是写死的-128到127。

    1. @IntrinsicCandidate
    2. public static Long valueOf(long l) {
    3. final int offset = 128;
    4. if (l >= -128 && l <= 127) { // will cache
    5. return LongCache.cache[(int)l + offset];
    6. }
    7. return new Long(l);
    8. }

    对了Float和 Double是没有滴,毕竟是小数,能存的数太多了。

  • 相关阅读:
    武汉凯迪正大—高压信号发生器
    React 使用 Zustand 详细教程
    FLOPS的计算
    2023前端面试整理
    Java Spring Cloud XVIII 之 Kafka I
    ELK安装、部署、调试 (二) ES的安装部署
    ChatGpt提问艺术 prompt工程学习过程
    day07-缓存套餐
    前端总结——WebSocket
    那些年那些神码
  • 原文地址:https://blog.csdn.net/qq_51967234/article/details/138141221