JUC-不可变

26 阅读4分钟

一、日期转换问题

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 解决方式

  • 方式一:使用『锁』方式解决线程不安全问题
@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();
        }
    }
}
  • 方式二:使用『不可变类』方式解决解决线程不安全问题

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();

        }
    }
}
  • 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);
    }	
  • 注意
    • 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
    }
}

四、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);
    }
}

  • 示意图

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

五、无状态设计

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

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