JUC学习之不可变

x33g5p2x  于2022-01-04 转载在 其他  
字(7.5k)|赞(0)|评价(0)|浏览(338)

日期转换的问题

问题提出:

下面的代码在运行时,由于 SimpleDateFormat 不是线程安全的

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

有很大几率出现 java.lang.NumberFormatException 或者出现不正确的日期解析结果,例如:

  1. 19:10:40.859 [Thread-2] c.TestDateParse - {}
  2. java.lang.NumberFormatException: For input string: ""
  3. at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  4. at java.lang.Long.parseLong(Long.java:601)
  5. at java.lang.Long.parseLong(Long.java:631)
  6. at java.text.DigitList.getLong(DigitList.java:195)
  7. at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
  8. at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
  9. at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
  10. at java.text.DateFormat.parse(DateFormat.java:364)
  11. at cn.itcast.n7.TestDateParse.lambda$test1$0(TestDateParse.java:18)
  12. at java.lang.Thread.run(Thread.java:748)
  13. 19:10:40.859 [Thread-1] c.TestDateParse - {}
  14. java.lang.NumberFormatException: empty String
  15. at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
  16. at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
  17. at java.lang.Double.parseDouble(Double.java:538)
  18. at java.text.DigitList.getDouble(DigitList.java:169)
  19. at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
  20. at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
  21. at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
  22. at java.text.DateFormat.parse(DateFormat.java:364)
  23. at cn.itcast.n7.TestDateParse.lambda$test1$0(TestDateParse.java:18)
  24. at java.lang.Thread.run(Thread.java:748)
  25. 19:10:40.857 [Thread-8] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  26. 19:10:40.857 [Thread-9] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  27. 19:10:40.857 [Thread-6] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  28. 19:10:40.857 [Thread-4] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  29. 19:10:40.857 [Thread-5] c.TestDateParse - Mon Apr 21 00:00:00 CST 178960645
  30. 19:10:40.857 [Thread-0] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  31. 19:10:40.857 [Thread-7] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
  32. 19:10:40.857 [Thread-3] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951

SimpleDateFormate为什么是线程不安全的

解决方法一: 加同步锁

  1. package Immuate;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.text.SimpleDateFormat;
  4. @Slf4j
  5. public class Main
  6. {
  7. public static void main(String[] args)
  8. {
  9. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  10. for (int i = 0; i < 10; i++)
  11. {
  12. new Thread(() ->
  13. {
  14. try {
  15. synchronized (sdf)
  16. {
  17. log.debug("{}", sdf.parse("1951-04-21"));
  18. }
  19. } catch (Exception e) {
  20. log.error("{}", e);
  21. }
  22. }).start();
  23. }
  24. }
  25. }

解决思路二: 使用不可变对象

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

  1. package Immuate;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.text.SimpleDateFormat;
  4. import java.time.LocalDate;
  5. import java.time.format.DateTimeFormatter;
  6. @Slf4j
  7. public class Main
  8. {
  9. public static void main(String[] args)
  10. {
  11. DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  12. for (int i = 0; i < 10; i++) {
  13. new Thread(() -> {
  14. LocalDate date = dtf.parse("2018-10-01", LocalDate::from);
  15. log.debug("{}", date);
  16. }).start();
  17. }
  18. }
  19. }

可以看 DateTimeFormatter 的文档:

  1. @implSpec
  2. This class is immutable and thread-safe.

不可变对象,实际是另一种避免竞争的方式。

不可变设计

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

  1. public final class String
  2. implements java.io.Serializable, Comparable<String>, 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. }

final的使用

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

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

保护性拷贝

但有同学会说,使用字符串时,也有一些跟修改相关的方法啊,比如 substring 等,那么下面就看一看这些方法是如何实现的,就以 substring 为例:

  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. if (offset > value.length - count) {
  15. throw new StringIndexOutOfBoundsException(offset + count);
  16. }
  17. this.value = Arrays.copyOfRange(value, offset, offset+count);
  18. }

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

享元模式

简介: 定义 英文名称:Flyweight pattern. 当需要重用数量有限的同一类对象时

享元模式详解

包装类

在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

String 串池

BigDecimal BigInteger

问: 线程安全对象为什么在使用的时候需要上锁

因为他们单个方法的执行都可以保证线程安全性,但是多个方法的组合使用确无法保证线程安全性.

连接池案例

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

  1. package MockPool;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.concurrent.atomic.AtomicIntegerArray;
  4. @Slf4j
  5. public class Pool
  6. {
  7. //连接池的默认大小
  8. private int size;
  9. //连接池数组
  10. private Connection[] connections;
  11. //连接状态数组----> 0表示空闲, 1表示繁忙
  12. private AtomicIntegerArray states;
  13. //构造方法初始化
  14. public Pool(int size)
  15. {
  16. this.size=size;
  17. this.connections=new Connection[size];
  18. this.states=new AtomicIntegerArray(new int[size]);
  19. for (int i=0;i<size;i++)
  20. {
  21. connections[i]=new Connection("连接"+(i+1));
  22. }
  23. }
  24. //借取连接
  25. public Connection borrow()
  26. {
  27. while(true)
  28. {
  29. for(int i=0;i<this.size;i++)
  30. {
  31. //当前存在剩余的空闲连接
  32. if(states.get(i)==0)
  33. {
  34. //cas确保多线程下不会存在并发问题
  35. if(states.compareAndSet(i,0,1))
  36. {
  37. log.debug("borrow {}",connections[i]);
  38. return connections[i];
  39. }
  40. }
  41. }
  42. // 如果没有空闲连接,当前线程进入等待
  43. synchronized (this) {
  44. try {
  45. log.debug("wait...");
  46. this.wait();
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }
  52. }
  53. // 6. 归还连接
  54. public void free(Connection conn)
  55. {
  56. for (int i = 0; i < size; i++) {
  57. if (connections[i] == conn) {
  58. states.set(i, 0);
  59. synchronized (this) {
  60. log.debug("free {}", conn);
  61. this.notifyAll();
  62. }
  63. break;
  64. }
  65. }
  66. }
  67. }
  1. //连接对象
  2. @Slf4j
  3. public class Connection
  4. {
  5. public Connection(String msg)
  6. {
  7. log.debug("消息: {}",msg);
  8. }
  9. }

使用连接池:

  1. public class Main
  2. {
  3. public static void main(String[] args) {
  4. Pool pool = new Pool(2);
  5. for (int i = 0; i < 5; i++) {
  6. new Thread(() -> {
  7. Connection conn = pool.borrow();
  8. try {
  9. Thread.sleep(new Random().nextInt(1000));
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. pool.free(conn);
  14. }).start();
  15. }
  16. }
  17. }

以上实现没有考虑:

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

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

final 原理

1. 设置 final 变量的原理

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

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

字节码

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

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

可见性

  • 写屏障(sfence)保证在该屏障之前的,对共享变量的改动,都同步到主存当中

  • 而读屏障(lfence)保证在该屏障之后,对共享变量的读取,加载的是主存中最新数据
    有序性

  • 写屏障会确保指令重排序时,不会将写屏障之前的代码排在写屏障之后

  • 读屏障会确保指令重排序时,不会将读屏障之后的代码排在读屏障之前

2. 获取 final 变量的原理

总结:

  • 变量加了final,例如int,数字比较小,就直接在栈内存中,数字超过短整型最大值,就放在常量池中
  • 不加final,就放在堆中
  • 显然堆的访问效率远不及栈

无状态

在 web 阶段学习时,设计 Servlet 时为了保证其线程安全,都会有这样的建议,不要为 Servlet 设置成员变量,这
种没有任何成员变量的类是线程安全的
因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为【无状态】

本章小结

  • 不可变类使用
  • 不可变类设计
  • 原理方面
  • final
  • 模式方面
  • 享元

相关文章