JUC高并发编程-共享模型之不可变

共享模型之不可变

日期转换的问题

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

1
2
3
4
5
6
7
8
9
10
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();
}

​ 输出:

1
2
3
4
5
6
7
8
9
10
11
Exception in thread "Thread-3" Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "1951."
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Long.parseLong(Long.java:692)
at java.base/java.lang.Long.parseLong(Long.java:817)
at java.base/java.text.DigitList.getLong(DigitList.java:195)
at java.base/java.text.DecimalFormat.parse(DecimalFormat.java:2123)
at java.base/java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1933)
at java.base/java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1541)
at java.base/java.text.DateFormat.parse(DateFormat.java:393)
at com.heu.test.TestDate.lambda$main$0(TestDate.java:21)
at java.base/java.lang.Thread.run(Thread.java:834)

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

1
2
3
4
5
6
7
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
LocalDate date = dtf.parse("2018-10-01", LocalDate::from);
log.debug("{}", date);
}).start();
}

不可变设计

String类中不可变的体现:

1
2
3
4
5
6
7
8
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 修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性。
保护性拷贝

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
// 上面是一些校验,下面才是真正的创建新的String对象
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}

我们发现其内部是调用 String 的构造方法创建了一个新字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
}
// 上面是一些安全性的校验,下面是给String对象的value赋值,新创建了一个数组来保存String对象的值
this.value = Arrays.copyOfRange(value, offset, offset+count);
}

模式之享元

简介

享元定义英文名称:Flyweight pattern。当需要重用数量有限的同一类对象时,归类为:Structual patterns。

体现

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

1
2
3
4
5
6
7
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);
}
  • Byte, Short, Long 缓存的范围都是 -128~127。

  • Character 缓存的范围是 0~127。

  • Integer 的默认范围是 -128~127,最小值不能变,但最大值可以通过调整虚拟机参数 “-Djava.lang.Integer.IntegerCache.high “来改变。

  • Boolean 缓存了 TRUE 和 FALSE

final的原理

设置 final 变量的原理

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

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

字节码:

1
2
3
4
5
6
7
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 变量的赋值操作都必须在定义时或者构造器中进行初始化赋值,并且发现 final 变量的赋值也会通过 putfield 指令来完成,同样在这条指令之后也会加入写屏障,保证在其它线程读到它的值时不会出现为 0 的情况。

-------------本文结束感谢您的阅读-------------