• Java并发编程学习笔记6——共享模型之不可变


    目录

    1、日期转换的问题

    2、不可变设计

    2.1、final的使用

    2.2、保护性拷贝

    3、享元模式

    3.1、简介

    3.2、体现

    3.2.1、包装类

    3.2.2、String串池

    3.2.3、BigDecimal BigInteger

    3.3、DIY

    4、final原理

    4.1、设置final变量的原理

    5、无状态


    1、日期转换的问题

    1. @Slf4j
    2. public class Test1 {
    3. public static void main(String[] args) {
    4. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    5. for (int i = 0; i < 10; i++) {
    6. new Thread(()->{
    7. try {
    8. log.debug("{}", sdf.parse("1951-04-21"));
    9. } catch (Exception e) {
    10. log.error("{}", e);
    11. }
    12. }).start();
    13. }
    14. }
    15. }

    上面的代码在运行时,由于SimpleDateFormat不是线程安全的,有很大几率出现java.lang.NumberFormatException或者出现不正确的日期解析结果。有以下方法可以解决:

    1. @Slf4j
    2. public class Test1 {
    3. public static void main(String[] args) {
    4. method1();
    5. }
    6. // 方法1
    7. private static void method1() {
    8. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    9. for (int i = 0; i < 10; i++) {
    10. new Thread(()->{
    11. synchronized (sdf) {
    12. try {
    13. log.debug("{}", sdf.parse("1951-04-21"));
    14. } catch (Exception e) {
    15. log.error("{}", e);
    16. }
    17. }
    18. }).start();
    19. }
    20. }
    21. // 方法2
    22. private static void method2() {
    23. DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    24. for (int i = 0; i < 10; i++) {
    25. new Thread(()->{
    26. TemporalAccessor parse = dtf.parse("1951-04-21");
    27. log.debug("{}", parse);
    28. }).start();
    29. }
    30. }
    31. }
    32. 结果:
    33. 16:38:55.496 [Thread-3] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    34. 16:38:55.496 [Thread-4] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    35. 16:38:55.497 [Thread-9] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    36. 16:38:55.495 [Thread-2] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    37. 16:38:55.497 [Thread-6] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    38. 16:38:55.496 [Thread-0] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    39. 16:38:55.496 [Thread-1] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    40. 16:38:55.497 [Thread-7] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    41. 16:38:55.496 [Thread-5] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
    42. 16:38:55.497 [Thread-8] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21

    2、不可变设计

    另一个大家更为熟悉的String类也是不可变的,以它为例,说明以下不可变设计的要素。

    1. public final class String
    2. implements java.io.Serializable, Comparable, CharSequence {
    3. /** The value is used for character storage. */
    4. private final char value[];
    5. /** Cache the hash code for the string */
    6. private int hash; // Default to 0
    7. // ...
    8. }

    2.1、final的使用

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

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

    2.2、保护性拷贝

    1. public String subString(int beginIndex) {
    2. if (beginIndex < 0) {
    3. throw new StringIndexOutOfBoundsException(beginIndex);
    4. }
    5. int subLen = value.length - beginIndex;
    6. if (subLen < 0) {
    7. throw new StringIndexOutOfBoundsException(subLen);
    8. }
    9. return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    10. }

    发现其内部是调用String的构造方法创建了一个新字符串,再进入这个构造看看,是否对final char[] value 做出了修改:

    1. public String(char value[], int offset, int count) {
    2. if (offset < 0) {
    3. throw new StringIndexOutOfBoundsException(offset);
    4. }
    5. if (count <= 0) {
    6. if (count < 0) {
    7. throw new StringIndexOutOfBoundsException(count);
    8. }
    9. if (offset <= value.length) {
    10. this.value = "".value;
    11. return;
    12. }
    13. }
    14. // Note: offset or count might be near -1>>>1.
    15. if (offset > value.length - count) {
    16. throw new StringIndexOutOfBoundsException(offset + count);
    17. }
    18. this.value = Arrays.copyOfRange(value, offset, offset+count);
    19. }

    结果发现也没有,构造新字符串时,会生成新的char[] value,对内容进行复制。这种通过创建副本对象来避免共享的手段称之为【保护性拷贝(defensive copy)】。

    3、享元模式

    3.1、简介

    定义:享元模式(Flyweight pattern),当需要重用数量有限的同一类对象时。

    3.2、体现

    3.2.1、包装类

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

    1. public static Long valueOf(long l) {
    2. final int offset = 128;
    3. if (l >= -128 && l <= 127) { // will cache
    4. return LongCache.cache[(int)l + offset];
    5. }
    6. return new Long(l);
    7. }

    注意:Byte,Short,Long缓存的范围都是-128~127;Character缓存的范围是0~127;Integer的默认范围是-128~127,最小值不能变,但最大值可以通过调整虚拟机参数 -Djava.lang.Integer.IntegerCache.high来改变;Boolean缓存了TRUE和FALSE。

    3.2.2、String串池

    3.2.3、BigDecimal BigInteger

    3.3、DIY

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

    1. public class Test2 {
    2. public static void main(String[] args) {
    3. Pool pool = new Pool(2);
    4. for (int i = 0; i < 5; i++) {
    5. new Thread(()->{
    6. Connection conn = pool.borrow();
    7. try {
    8. Thread.sleep(new Random().nextInt(1000));
    9. } catch (InterruptedException e) {
    10. e.printStackTrace();
    11. }
    12. pool.free(conn);
    13. }).start();
    14. }
    15. }
    16. }
    17. @Slf4j
    18. class Pool {
    19. // 连接池大小
    20. private final int poolSize;
    21. // 连接数组
    22. private Connection[] conns;
    23. // 连接是否被占用 标记
    24. private AtomicIntegerArray states;
    25. // 初始化连接池
    26. public Pool(int poolSize) {
    27. this.poolSize = poolSize;
    28. this.conns = new Connection[poolSize];
    29. this.states = new AtomicIntegerArray(new int[poolSize]);
    30. for (int i = 0; i
    31. conns[i] = new MockConnection("连接" + (i + 1));
    32. }
    33. }
    34. // 从连接池暂借连接
    35. public Connection borrow() {
    36. while(true) {
    37. for (int i = 0; i < poolSize; i++) {
    38. if (states.get(i) == 0) {
    39. if (states.compareAndSet(i, 0, 1)) {
    40. log.debug("borrow {}", conns[i]);
    41. return conns[i];
    42. }
    43. }
    44. }
    45. // 如果没有空闲连接,当前线程进入等待,不让CPU空转
    46. synchronized (this) {
    47. try {
    48. log.debug("wait...");
    49. this.wait();
    50. } catch (InterruptedException e) {
    51. e.printStackTrace();
    52. }
    53. }
    54. }
    55. }
    56. // 归还连接至连接池
    57. public void free(Connection conn) {
    58. for (int i = 0; i < poolSize; i++) {
    59. if (conns[i] == conn) {
    60. states.set(i, 0);
    61. synchronized (this) {
    62. log.debug("free {}", conn);
    63. this.notifyAll();
    64. }
    65. break;
    66. }
    67. }
    68. }
    69. }
    70. @Data
    71. class MockConnection implements Connection {
    72. private String name;
    73. public MockConnection(String name) {
    74. this.name = name;
    75. }
    76. @Override
    77. public String toString() {
    78. return "MockConnection{" +
    79. "name='" + name + '\'' +
    80. '}';
    81. }
    82. @Override
    83. public Statement createStatement() throws SQLException {
    84. return null;
    85. }
    86. // ...
    87. }
    88. 结果:
    89. 10:46:30.387 [Thread-0] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
    90. 10:46:30.387 [Thread-2] DEBUG com.multiThreads.Test17.Pool - wait...
    91. 10:46:30.387 [Thread-1] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接2'}
    92. 10:46:30.390 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
    93. 10:46:30.390 [Thread-3] DEBUG com.multiThreads.Test17.Pool - wait...
    94. 10:46:30.486 [Thread-1] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接2'}
    95. 10:46:30.486 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
    96. 10:46:30.486 [Thread-3] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接2'}
    97. 10:46:30.486 [Thread-2] DEBUG com.multiThreads.Test17.Pool - wait...
    98. 10:46:30.912 [Thread-0] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}
    99. 10:46:30.912 [Thread-2] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
    100. 10:46:30.913 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
    101. 10:46:31.361 [Thread-2] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}
    102. 10:46:31.361 [Thread-4] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
    103. 10:46:31.484 [Thread-3] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接2'}
    104. 10:46:31.924 [Thread-4] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}

    以上实现没有考虑:

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

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

    4、final原理

    4.1、设置final变量的原理

    理解了volatile原理,再对比final的实现就比较简单了。

    1. class TestFinal {
    2. final int a = 20;
    3. }

    字节码:

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

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

    5、无状态

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

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

  • 相关阅读:
    【活着活着就老了-冯唐】阅后
    FlinkSQL之Windowing TVF
    Studio 3T for MongoDB的介绍及语法简单介绍
    pandas的一些函数
    自定义prometheus exporter实现监控阿里云RDS
    springboot @Validated验证
    Java#25(常见算法: 查找算法)
    STM32-CAN
    [线程安全问题] 多线程到底可能会带来哪些风险?
    Kubernetes(k8s)的流量负载组件Service基础介绍和原理讲解、IPVS的开启
  • 原文地址:https://blog.csdn.net/weixin_44623055/article/details/126288127