併發編程進階之----共享模型之不可變
1、日期轉換的問題
問題提出
下面的代碼在運行時,由於 SimpleDateFormat 不是線程安全的
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();
}
有很大機率出現 java.lang.NumberFormatException 或者出現不正確的日期解析結果,例如:
19:10:40.859 [Thread-2] c.TestDateParse - {}
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at cn.itcast.n7.TestDateParse.lambda$test1$0(TestDateParse.java:18)
at java.lang.Thread.run(Thread.java:748)
19:10:40.859 [Thread-1] c.TestDateParse - {}
java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.text.DigitList.getDouble(DigitList.java:169)
at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at cn.itcast.n7.TestDateParse.lambda$test1$0(TestDateParse.java:18)
at java.lang.Thread.run(Thread.java:748)
19:10:40.857 [Thread-8] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-9] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-6] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-4] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-5] c.TestDateParse - Mon Apr 21 00:00:00 CST 178960645
19:10:40.857 [Thread-0] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-7] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
19:10:40.857 [Thread-3] c.TestDateParse - Sat Apr 21 00:00:00 CST 1951
思路 - 同步鎖
這樣雖能解決問題,但帶來的是性能上的損失,並不算很好:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < 50; i++) {
new Thread(() -> {
synchronized (sdf) {
try {
log.debug("{}", sdf.parse("1951-04-21"));
} catch (Exception e) {
log.error("{}", e);
}
}
}).start();
}
思路 - 不可變
如果一個對象在不能夠修改其內部狀態(屬性),那麼它就是線程安全的,因爲不存在併發修改啊!這樣的對象在Java 中有很多,例如在 Java 8 後,提供了一個新的日期格式化類:
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();
}
可以看 DateTimeFormatter 的文檔:
@implSpec
This class is immutable and thread-safe.
不可變對象,實際是另一種避免競爭的方式。
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 的
保護性拷貝
但有人會說,使用字符串時,也有一些跟修改相關的方法啊,比如 substring 等,那麼下面就看一看這些方法是如何實現的,就以 substring 爲例:
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
發現其內部是調用 String 的構造方法創建了一個新字符串,再進入這個構造看看,是否對 final char[] value 做出了修改:
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;
}
}
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
//生成新的 char[] value,對內容進行復制
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
結果發現也沒有,構造新字符串對象時,會生成新的 char[] value,對內容進行復制 。這種通過創建副本對象來避免共享的手段稱之爲【保護性拷貝(defensive copy)】
3、 模式之享元
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);
}
3、DIY
例如:一個線上商城應用,QPS 達到數千,如果每次都重新創建和關閉數據庫連接,性能會受到極大影響。 這時預先創建好一批連接,放入連接池。一次請求到達後,從連接池獲取連接,使用完畢後再還回連接池,這樣既節約了連接的創建和關閉時間,也實現了連接的重用,不至於讓龐大的連接數壓垮數據庫。
public class Test3 {
public static void main(String[] args) {
/*使用連接池*/
Pool pool = new Pool(2);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
Connection conn = pool.borrow();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.free(conn);
}).start();
}
}
}
@Slf4j(topic = "c.Pool")
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]);//使用AtomicIntegerArray保證states的線程安全
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)) {//使用compareAndSet保證線程安全
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 conn) {
for (int i = 0; i < poolSize; i++) {
if (connections[i] == conn) {
states.set(i, 0);
synchronized (this) {
log.debug("free {}", conn);
this.notifyAll();
}
break;
}
}
}
}
class MockConnection implements Connection {
private String name;
public MockConnection(String name) {
this.name = name;
}
@Override
public String toString() {
return "MockConnection{" +
"name='" + name + '\'' +
'}';
}
.........
4、final 原理
4.1 設置 final 變量的原理
理解了 volatile 原理,再對比 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: retu
發現 final 變量的賦值也會通過 putfield 指令來完成,同樣在這條指令之後也會加入寫屏障,保證在其它線程讀到它的值時不會出現爲 0 的情況。