原创

jdk中一些精妙的设计(源码学习,持续更新、、、)

一、基础工具类


1、Objects.requireNonNull

public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}

经典点:

  • 失败尽早(Fail Fast)

  • 替代一堆 if (xxx == null) 的防御代码

  • Spring / JDK 内部大量使用

 思想:错误不是避免的,是要尽早暴露的!

2、String.equals

public boolean equals(Object anObject) {
    if (this == anObject) return true;
    if (anObject instanceof String) {
        String aString = (String)anObject;
        int n = value.length;
        if (n == aString.value.length) {
            char v1[] = value;
            char v2[] = aString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i]) return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

经典点:

  • 引用相等优先

  • 长度先判(性能)

  • 再逐字符比较

  思想:80% 情况用最快的方式返回!

3、Integer.valueOf

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high) //-128到127
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

经典点

  • 对象缓存

  • 解释了为什么 Integer == 有时对、有时错

 思想:用空间换时间,但要让使用者无感

4、IntegerCache

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            CDS.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }


正文到此结束