Effective Java(with Spring core)

电子原版目录以及概要 请购买实体书籍,支持作者、翻译以及出版社 Creating and Destroying Objects 用静态工厂方法代替构造器 public static Boolean valueOf(boolean b){ return b ? Boolean.TRUE : Boolean.FALSE; } 静态工厂方法与设计模式中的工厂方法模式不同。并不能直接对应设计模式的工厂方法。 优势 有名字(像这种BigInteger.probablePrime(int bitLength,Random rnd)) 不必每次调用他们的时候,都创建一个新对象。像Integer.MAX_VALUE = 0x7fffffff(享元Flyweight模式)真正的享元模式如下,Integer中有个私有静态类,叫IntergeCache 可以返回原返回类型的任何子类型的对象。Java8允许接口中含有静态方法,Java9允许接口中有私有的静态方法,但是静态域和静态成员变量仍然需要是公有的。 所返回的对象的类可以随着每次调用而发生变化,这取决于静态工厂方法的参数值。 方法返回的对象所属的类,在便携包含该静态工厂方法的类时可以不存在。 public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; /** * 这里定义了最大值,也就是说这个可以配置 * -XX:AutoBoxCacheMax=NNN,这里的 NNN 表示最大值是多少,只能改最大值,不能改最小值。 * 在设置了-XX:+AggressiveOpts启动参数后,AutoBoxCacheMax的默认值会被修改为20000并且生效。 * 这里的 -XX:+AggressiveOpts 是表示加快编译 * aggressive adj.好争斗的, 挑衅的, 侵略性的 * export JAVA_OPTS="-Xms2048m -Xmx2048m"。 * 合起来翻译 积极的选择 * - Tired compilers (hoping that it will make it into JDK7) * - Scalar replacement (and I am still hoping that this will remove some of the memory throughput preassure 64-bit brought) * EA and stack allocation * Code cache */ String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} } 缺点 ...

June 18, 2020