JUC并发编程共享模型之不可变(六)

6.1 日期转换的问题

SimpleDateFormat 不是线程安全的

@Slf4j
public class SimpleDateFormatTest {
    
    
    public static void main(String[] args) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
    
    
            new Thread(() -> {
    
    
                try {
    
    
                    log.debug("{}", sdf.parse("1951-04-21"));
                } catch (Exception e) {
    
    
                    log.error("{}", e);
                }
            }).start();
        }
    }
}

会出现日期解析不正确的结果

在这里插入图片描述

给SimpleDateFormat 加锁,但是性能有损失

@Slf4j
public class SimpleDateFormatTest {
    
    
    public static void main(String[] args) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
    
    
            new Thread(() -> {
    
    
                synchronized (sdf){
    
    
                    try {
    
    
                        log.debug("{}", sdf.parse("1951-04-21"));
                    } catch (Exception e) {
    
    
                        log.error("{}", e);
                    }
                }
            }).start();
        }
    }
}

在这里插入图片描述

不可变的时间类(线程安全)

如果一个对象在不能够修改其内部状态,那么它就是线程安全的,因为不能修改,所以不存在并发修改!这样的对象java中有很多,例如java 8后,提供了一个新的日期格式化类:

@Slf4j
public class DateTimeFormatterTest01 {
    
    

    public static void main(String[] args) {
    
    
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(int i = 0; i < 10; i++){
    
    
            new Thread(() -> {
    
    
                LocalDate localDate = dtf.parse("2018-03-24", LocalDate::from);
                log.debug("{}", localDate);
            }).start();
        }
    }
}

在这里插入图片描述

  • 不可变 + 线程安全 在这里插入图片描述

6.2 不可变设计

另一个熟悉的 String 类也是不可变的,不可变设计的要素

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
    
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0
    
    // ....
}

final的使用

发现该类、类中所有属性都是final的

  • 属性用 final 修饰保证了该属性是只读的,不能修改
  • 类用 final 修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性

保护性拷贝

使用字符串的修改方法,都是内部调用了String的构造方法创建了一个新字符串

    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;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }
  • 构造新字符串对象时,会生成新的 char[] value,对内容进行复制,这种通过创建副本对象来避免共享的手段称之为 保护性拷贝

6.3 享元模式

6.3.1. 简介

享元模式运用共享技术有效地支持大量细粒度的对象。主要用于减少创建对象的数量,以减少内存占用和提高性能。

这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

6.3.2.体现

包装类

在JDK 中 Boolean,Byte,Short,Integer,Character 等包装类提供了 valueOf 方法,例如Long的 valueOf 会缓存 -128 - 127 之间的Long 对象,在这个范围之间会重用对象,大于这个范围,才会新建Long对象:

    public static Integer valueOf(int i) {
    
    
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  • Byte, Short, Long 缓存的范围都是 -128~127

  • Character 缓存的范围是 0~127

  • Integer的默认范围是 -128~127

    • 最小值不能变

    • 但最大值可以通过调整虚拟机参数

      -Djava.lang.Integer.IntegerCache.high` 来改变

  • Boolean 缓存了 TRUE和 FALSE

String 串池

  1. String str1=new String(“This is a string”);
  2. String str2 =“This is a string”;
  • 通过关键字new 定义:
    • 先在字符串常量池查找
      • 如果存在,则不另外开辟空间,保证字符常量区只有一个“This is a string”,节省空间。然后在堆区开辟一个空间,存放new出来的String对象,并在栈区开辟空间,存放变量名称str1,str1指向堆区new出来的String对象
      • 如果不存在,则在字符串常量池开辟一个内存空间,存放"This is a string"
  • 直接定义
    • 在字符串常量区查找是否存在“This is a string”常量
      • 如果不存在,则在字符串常量区开辟一个内存空间,存放“This is a string”
      • 如果存在,不另外开辟空间,在栈区开辟空间,存放变量名称str2,str2指向字符串常量池“This is a string”的内存地址

6.3.3 DIY

QPS:Queries Per Second ,意思是“每秒查询率”,是一台服务器每秒能够相应的查询次数,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准。

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

package com.lv.juc;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ExceptionInterceptor;
import com.mysql.jdbc.Extension;
import com.mysql.jdbc.MySQLConnection;
import com.mysql.jdbc.log.Log;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author 晓风残月Lx
 * @date 2023/3/24 9:29
 */
@Slf4j
public class ThreadPoolMain {
    
    

    public static void main(String[] args) {
    
    
        Pool pool = new Pool(3);
        for(int i = 0; i < 5; i++){
    
    
            new Thread(() -> {
    
    
                Connection conn = pool.borrow();
                try{
    
    
                    Thread.sleep(new Random().nextInt(1000));
                }catch (Exception e){
    
    
                    e.printStackTrace();
                }
                pool.free(conn);
            }).start();
        }
    }

}

@Slf4j
class Pool {
    
    
    // 1.连接池大小
    private final int poolSize;

    // 2.连接对象数组
    private Connection[] connections;

    // 3.连接状态数组 0 表示空闲 1 表示繁忙
    private AtomicIntegerArray states;

    // 4.构造方法初始化
    public Pool(int poolSize){
    
    
        this.poolSize = poolSize;
        this.connections = new Connection[poolSize];
        this.states = new AtomicIntegerArray(new int[poolSize]);
        for(int i = 0; i < poolSize; i++){
    
    
            connections[i] = new MockConnection("连接"+(i+1));
        }
    }

    // 5.借连接
    public Connection borrow(){
    
    
        while (true){
    
    
            for (int i = 0; i < poolSize; i++){
    
    
                // 获取空闲连接
                if (states.get(i) == 0){
    
    
                    if (states.compareAndSet(i, 0, 1)){
    
    
                        log.debug("borrow {}", connections[i]);
                        return connections[i];
                    }
                }
            }

            // 如果没有空闲连接,当前线程进入等待
            synchronized (this){
    
    
                try {
    
    
                    log.debug("wait....");
                    this.wait();
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }


    // 6. 归还连接
    public void free(Connection connection){
    
    
        for(int i = 0; i < poolSize; i++){
    
    
            if (connections[i] == connection){
    
    
                states.set(i,0);
                synchronized (this){
    
    
                    log.debug(" free {}",connection);
                    this.notifyAll();
                }
                break;
            }
        }
    }


}

@Slf4j
class MockConnection implements Connection{
    
    
   // 实现一下即可,不用写,构造方法要写一下
}

在这里插入图片描述

以上实现没有考虑

  • 连接的动态增长和收缩
  • 连接保活(可用性检测)
  • 等待超时处理
  • 分布式hash

对于关系型数据库,有比较成熟的连接池实现,例如c3p0, druid等 对于更通用的对象池,可以考虑使用apache commons pool,例如redis连接池可以参考jedis中关于连接池的实现

6.4 final 原理

final的原理: final底层也是通过内存屏障实现的,它与volatile一样。

  • 对final变量的写指令加入写屏障。也就是类初始化的赋值的时候会加上写屏障。
  • 对final变量的读指令加入读屏障。加载内存中final变量的最新值。

1.设置final变量的原理

public class TestFinal {
    
    
    final int a = 20;
}

字节码:

0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 20
7: putfield #2 // Field a:I
 <-- 写屏障
10: return

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

2.获取final变量的原理

@Slf4j
public class TestFinal {
    
    
    static final int a = 20;

    public static void main(String[] args) {
    
    
        System.out.println(a);
    }
}
 <-- 读屏障
0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream; 
3: bipush        20
5: invokevirtual #4                  // Method java/io/PrintStream.println:(I)V
8: return

发现final变量的获取也会通过getstatic 指令完成,同样这条指令之前也会加入读屏障,保证其他线程读到它的值是加载内存中final变量的最新值

6.5 无状态

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

  • 因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为 无状态
    • 不可变:有成员变量,有状态,但是不可改变的,线程安全
    • 无状态:无成员变量,无状态,也就不可变娄,线程安全

猜你喜欢

转载自blog.csdn.net/m0_55993923/article/details/129746034