• JUC-不可变


    一、日期转换问题

    1.1 问题提出

    因为 SimpleDateFormat 类不是线程安全的,所以多线程场景下执行会出现异常。

    • 代码示例
    @Slf4j
    public class UnSafeDateSample {
    
        public static void main(String[] args) {
    
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
            for (int i = 0; i < 5; i++) {
    
                new Thread(() -> {
    
                    try {
                        Date date = dateFormat.parse("2020-02-22");
                        log.debug("date={}", date);
                    } catch (ParseException e) {
                        log.error("format error={}", e.getMessage());
                        // 第一次运行结果:java.lang.NumberFormatException: empty String
                        // 第二次运行结果:java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 19
                    }
    
                }).start();
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    1.2 解决方式

    • 方式一:使用『锁』方式解决线程不安全问题
    @Slf4j
    public class SafeDateSample {
    
        public static void main(String[] args) {
    
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
            for (int i = 0; i < 5; i++) {
    
                new Thread(() -> {
    
                    synchronized (dateFormat) {
                        try {
                            Date date = dateFormat.parse("2020-02-22");
                            log.debug("date={}", date);
                            // date=Sat Feb 22 00:00:00 CST 2020
                            // ...
                        } catch (ParseException e) {
                            log.error("format error={}", e.getMessage());
                        }
                    }
    
                }).start();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 方式二:使用『不可变类』方式解决解决线程不安全问题

    Java 8 后,提供了一个新的日期格式化类。

    @Slf4j
    public class SafeDateSample {
    
        public static void main(String[] args) {
    
            DateTimeFormatter dateformate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
            for (int i = 0; i < 5; i++) {
    
                new Thread(() -> {
                    LocalDate parse = dateformate.parse("2020-02-22", LocalDate::from);
                    log.debug("date={}", parse);
                    // date=2020-02-22
                    // ...
                }).start();
    
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • DateTimeFormatter 类是不可变的,安全的。

    二、不可变设计

    • 最为熟悉的 String 类也是不可变的,它的设计要素有以下两点:
      • 属性用 final 修饰保证了该属性是只读的,不能修改。
      • 类用 final 修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性。

    三、享元模式

    享元模式(Flyweight pattern) 定义 :尽可能多地与其他类似对象共享数据,从而最大限度地减少内存的使用

    3.1 在 JDK 中的运用

    体现在:包装类String 串池、BigDecimalBigInteger

    • 包装类
      • JDKBooleanByteShortIntegerLongCharacter 等包装类提供了 valueOf() 方法。
      • 此处以 Long类 的 valueOf() 方法为例(Long类 的 valueOf() 会缓存 -128~127 之间的 Long 对象,在这个范围之间会重用对象,大于这个范围,才会新建 Long 对象):
        @HotSpotIntrinsicCandidate
        public static Long valueOf(long l) {
            final int offset = 128;
            if (l >= -128 && l <= 127) { // will cache
                return LongCache.cache[(int)l + offset];
            }
            return new Long(l);
        }	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 注意
      • ByteShortLong 缓存的范围都是 -128~127。
      • Character 缓存的范围是 0~127。
      • Integer 的默认范围是 -128~127。(备注:最小值不能变,但最大值可以通过调整虚拟机参数 -Djava.lang.Integer.IntegerCache.high 来改变。)
      • Boolean 缓存了 TRUEFALSE

    3.2 自定义使用

    需求背景:一个线上商城应用,QPS 达到数千,如果每次都重新创建和关闭数据库连接,性能会受到极大影响。 这时预先创建好一批连接,放入连接池。一次请求到达后,从连接池获取连接,使用完毕后再还回连接池,这样既节约了连接的创建和关闭时间,也实现了连接的重用,不至于让庞大的连接数压垮数据库。

    • 代码示例
    @Slf4j
    public class PoolSample {
    
        /* *
         * 连接池大小。
         */
    
        private final int poolSize;
    
        /* *
         * 连接对象数组。
         */
    
        private final Connection[] connections;
    
        /* *
         * 连接状态数组。
         */
    
        private final AtomicIntegerArray statesArray;
    
        @Getter
        private enum States {
            // 0:表示空闲。
            Free(0),
            // 1:表示繁忙。
            Busy(1);
    
            private final int code;
    
            States(int code) {
                this.code = code;
            }
        }
    
        /**
         * 初始化构造器。
         *
         * @param poolSize 池大小
         */
    
        public PoolSample(int poolSize) {
            this.poolSize = poolSize;
            this.connections = new Connection[poolSize];
            this.statesArray = new AtomicIntegerArray(new int[poolSize]);
            for (int i = 0; i < poolSize; i++) {
                connections[i] = new MockConnection("connection_" + (i + 1));
            }
        }
    
        /* *
         * 获取连接。
         */
    
        public Connection get() {
            while (true) {
                for (int i = 0; i < connections.length; i++) {
                    // 获取空闲连接。
                    if (States.Free.getCode() == this.statesArray.get(i)) {
                        // CAS操作。
                        if (this.statesArray.compareAndSet(i, States.Free.getCode(), States.Busy.getCode())) {
                            log.debug("[{}] get connection=[{}]", Thread.currentThread().getName(), connections[i]);
                            return connections[i];
                        }
                    }
                }
                // 如果没有空闲连接,则当前线程进入等待。
                synchronized (this) {
                    try {
                        log.debug("[{}],wait...", Thread.currentThread().getName());
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * 归还连接。
         *
         * @param con 连接对象
         */
    
        public void revert(Connection con) {
            for (int i = 0; i < poolSize; i++) {
                if (connections[i] == con) {
                    statesArray.set(i, 0);
                    log.debug("[{}],is reverted", connections[i]);
                    synchronized (this) {
                        log.debug("[{}],is free", (con));
                        this.notifyAll();
                    }
                    break;
                }
            }
        }
    }
    
    class MockConnection implements Connection {
    
        private final String name;
    
        public MockConnection(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return name;
        }
    
        // 备注:其他方法为默认接口实现,此处省略...。
    }
    
    
    class ConnectionTests {
    
        public static void main(String[] args) {
    
            // 创建大小为2的连接池。
            PoolSample pool = new PoolSample(2);
            // 创建3个线程去使用连接池。
            for (int i = 0; i < 3; i++) {
                new Thread(() -> {
                    // 获取连接。
                    Connection conn = pool.get();
                    try {
                        // 随机休眠。
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 返还连接。
                    pool.revert(conn);
                }, "t_" + i).start();
            }
    
            // [t_2],wait...
            // [t_1] get connection=[connection_1]
            // [t_0] get connection=[connection_2]
            // [connection_2],is reverted
            // [connection_2],is free
            // [t_2] get connection=[connection_2]
            // [connection_1],is reverted
            // [connection_1],is free
            // [connection_2],is reverted
            // [connection_2],is free
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150

    四、final 原理

    4.1 设置 final 变量的原理

    • 示意图

    在这里插入图片描述

    • 发现 final 变量的赋值也会通过 putfield 指令来完成,同样在这条指令之后也会加入写屏障,保证在其它线程读到它的值时不会出现为 0 的情况。

    4.2 获取 final 变量的原理

    • 代码示例
    public class TestFinal {
    
        /* *
         * final变量 A -> 从『栈内存』中获取。
         */
    
        final static int A = 10;
    
        /* *
         * final变量 B -> 从『常量池』中获取。
         */
    
        final static int B = Short.MAX_VALUE + 1;
    
        /* *
         * 没有 final 修饰的变量 C -> 从『堆内存』中获取。
         */
    
        static int C = Short.MAX_VALUE + 1;
    
    }
    
    class UseFinal {
        public void test() {
            System.out.println(TestFinal.A);
            System.out.println(TestFinal.B);
            System.out.println(TestFinal.C);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 示意图

    在这里插入图片描述

    • 说明
      • 变量A:被 final 修饰,执行指令 bipush 10 。表示 A=10 不是从TestFinal类中获取,而是复制到了UseFinal类的栈内存中,直接从栈中获取,从而避免了变量A被共享
      • 变量BShort.MAX_VALUE 的值是32767,加1后为32768,超过了短整型的最大值,执行指令 ldc 。类加载时会将变量B的值复制到常量池,可以从常量池中获取,效率更高。
      • 变量C:不被 final 修饰时,执行指令 getstatic 。相当于读取的是共享内存堆中的值,效率低。

    五、无状态设计

    • web 阶段学习时,设计 Servlet 时为了保证其线程安全,都会有这样的建议,不要为 Servlet 设置成员变量,这种没有任何成员变量的类是线程安全的

    • 因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为无状态

    六、结束语


    “-------怕什么真理无穷,进一寸有一寸的欢喜。”

    微信公众号搜索:饺子泡牛奶

  • 相关阅读:
    如何配置AI参数SK接口
    C语言函数(2)
    C和指针 第15章 输入/输出函数 15.5 流I/O总览
    Redis--分布式缓存--三种集群的搭建之二 哨兵模式及原理(三)
    JVisualVM工具的使用
    前端设计模式之【迭代器模式】
    动态代理看这个就够了
    图片去水印免费软件哪个好?这几款软件值得一看
    Otsu阈值分割详解
    【MySQL】数据类型
  • 原文地址:https://blog.csdn.net/weixin_48776531/article/details/126826139