不可变

不可变

1、如果一个对象在不能够修改其内部状态(属性),那么它就是线程安全的,因为不存在并发修改

2、例

(1)String 类

(2)DateTimeFormatter 类

3、使用 final 修饰类、及类中属性

(1)属性用 final 修饰,保证该属性是只读的,不能修改

(2)类用 final 修饰,保证该类中的方法不能被覆盖,防止子类无意间破坏不可变性

4、保护性拷贝

(1)defensive copy

(2)通过创建副本对象,避免共享

(3)如:String 的 substring

(4)内部调用 String 的构造方法,创建一个新字符串

public String substring(int beginIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    int subLen = value.length - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}

(5)构造新字符串对象时,生成新的 char[] value,对内容进行复制

public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count <= 0) {
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        if (offset <= value.length) {
            this.value = "".value;
            return;
        }
    }
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }
    this.value = Arrays.copyOfRange(value, offset, offset+count);
}

 

享元模式

1、Flyweight pattern

2、应用场景:需要重用数量有限的同一类对象时

3、体现

(1)包装类,提供 valueOf 方法,缓存一定范围内的对象,在这个范围之间会重用对象,大于这个范围,才会新建对象

(2)String 字符串常量池

(3)BigDecimal、BigInteger

4、注意

(1)BigDecimal、BigInteger 仍需 CAS 操作类保护,是因为其单个方法线程安全,但组合方法线程不安全

(2)Byte、Short、Long 缓存范围:-128 ~ 127

(3)Character 缓存范围:0 ~ 127

(4)Integer 默认范围:-128 ~ 127,最小值不能变,可以通过调整虚拟机参数:-Djava.lang.Integer.IntegerCache.high,来改变最大值

(5)Boolean 缓存:TRUE、FALSE

posted @   半条咸鱼  阅读(22)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示