- 不可变类的使用
- 不可变类的设计
- 无状态类设计
下面的代码在运行时,由于 SimpleDateFormat 不是线程安全的
package unchange;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
@Slf4j(topic = "c.TestSimpleDataFormat")
public class TestSimpleDataFormat {
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();
}
}
}
有很大记录出现 java.lang.NumberFormatException 或者出现不正确的日期解析结果,例如:
16:08:29.855 c.TestSimpleDataFormat [Thread-0] - {}
java.lang.NumberFormatException: multiple points
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
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:2087)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at unchange.TestSimpleDataFormat.lambda$main$0(TestSimpleDataFormat.java:14)
at java.lang.Thread.run(Thread.java:748)
16:08:29.855 c.TestSimpleDataFormat [Thread-2] - {}
......
16:08:29.853 c.TestSimpleDataFormat [Thread-5] - Wed Feb 21 00:00:00 CST 1951
16:08:29.853 c.TestSimpleDataFormat [Thread-7] - Fri Apr 21 00:00:00 CST 1195
16:08:29.853 c.TestSimpleDataFormat [Thread-8] - Sat Apr 21 00:00:00 CST 1951
16:08:29.853 c.TestSimpleDataFormat [Thread-6] - Sat Apr 21 00:00:00 CST 1951
16:08:29.853 c.TestSimpleDataFormat [Thread-9] - Wed Apr 11 00:00:00 CST 1951
加锁,这样虽能解决问题,但带来的是性能上的损失,并不算很好:
package unchange;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
@Slf4j(topic = "c.TestSimpleDataFormat")
public class TestSimpleDataFormat {
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 中有很多,例如在 Java8 后,提供了一个新的日期格式化类:
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
LocalDate date = dtf.parse("2021-08-12", LocalDate::from);
log.debug("{}", date);
}).start();
}
}
可以看 DateTimeFormatter 的文档:
@implSpec
This class is immutable and thread-safe.
不可变对象是另一种避免竞争的方式。
另一个大家更为熟悉的 String 类也是不可变的,以它为例,说明一下不可变设计的要素
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
// final 修饰 只能赋值一次。但是只能保证引用不变!
private final char value[]; // 高版本变成 byte 数组了
/** Cache the hash code for the string */
private int hash; // Default to 0
// ...
}
发现该类、类中所有属性都是 final 的
- 属性用 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
做出了修改【JDK9 改为了用 byte 数组实现了】:
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,对内容进行复制 。这种通过创建副本对象来避免共享的手段称之为【保护性拷贝(defensive copy)】
英文名称:Flyweight pattern. 当需要重用数量有限的同一类对象时
wikipedia:A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects。
在 JDK 中 Boolean,Byte,Short,Integer,Long,Character 等包装类提供了 valueOf 方法,例如 Long 的 valueOf 会缓存 -128~127 之间的 Long 对象,在这个范围之间会重用对象,大于这个范围,才会新建 Long 对象。
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);
}
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
注意
- Byte, Short, Long 缓存的范围都是 -128~127
- Character 缓存的范围是 0~127
- Integer 的默认范围是 -128~127
- 最小值不能变
- 但最大值可以通过调整虚拟机参数
-Djava.lang.Integer.IntegerCache.high
来改变
- Boolean 缓存了 true 和 false
不可变,单个方法是安全的,但是多个方法的组合不一定是安全的!组合操作需要用原子操作保护!
package unchange;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicReference;
public class TestMyPool {
public static void main(String[] args) {
Pool pool = new Pool(2);
for (int i = 0; i < 10; i++) {
Thread th = new Thread(() -> {
Connection borrow = pool.borrow();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
pool.free(borrow);
}
});
th.start();
}
}
}
class Pool {
private final int poolSize;
private Connection[] connections;
private AtomicIntegerArray states;
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();
}
}
// 获得连接
public Connection borrow() {
while (true) {
for (int i = 0; i < poolSize; i++) {
if (states.get(i) == 0) {
while (true) {
// 下标为i的 数据从 0 变成 1
if (states.compareAndSet(i, 0, 1)) {
return connections[i];
}
}
}
}
// 如果没有空闲连接,当前线程进入等待
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void free(Connection connection) {
for (int i = 0; i < poolSize; i++) {
// 归还连接的线程,就是这个连接的持有者。
if (connections[i] == connection) {
states.set(i, 0);
}
}
synchronized (this) {
this.notifyAll();
}
}
// 归还连接
}
class MockConnection implements Connection {
// some code
}
CAS 适合短时运行的代码片段,获取数据库连接后,需要进行 CRUD,时间较长。CAS 不断空转浪费资源。因此选择的 wait,而 wait 需要用 sync 包裹。
以上实现没有考虑:
- 连接的动态增长
- 连接保活(可用性检测,保证是个活跃连接)
- 等待超时处理
- 分布式 hash
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 变量的赋值也会通过 putfield 指令来完成,同样在这条指令之后也会加入写屏障,保证在其它线程读到它的值时不会出现为 0 的情况
public class TestFinal {
static int A = 10; // 数字比较小就直接在栈内存中
final static int B = Short.MAX_VALUE + 1;
// 数字比较大,超过了 Short 的范围 就在常量池中
// 有 final 修饰 读的是常量池中的内容,不走 getstatic,
// 不加 final 就在堆中,读取的效率比不上加 final 的
final int a = 20;
final int b = Integer.MAX_VALUE;
public static void main(String[] args) {
System.out.println(TestFinal.A);
System.out.println(TestFinal.B);
System.out.println(new TestFinal().a);
System.out.println(new TestFinal().b);
}
}
字节码
stack=3, locals=1, args_size=1
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: bipush 10
5: invokevirtual #9 // Method java/io/PrintStream.println:(I)V
8: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
11: ldc #10 // int 32768
13: invokevirtual #9 // Method java/io/PrintStream.println:(I)V
16: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
19: new #8 // class finalz/TestFinal
22: dup
23: invokespecial #11 // Method "<init>":()V
26: invokestatic #12 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)L
java/lang/Object;
29: pop
30: bipush 20
32: invokevirtual #9 // Method java/io/PrintStream.println:(I)V
35: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
38: new #8 // class finalz/TestFinal
41: dup
42: invokespecial #11 // Method "<init>":()V
45: invokestatic #12 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)L
java/lang/Object;
48: pop
49: ldc #5 // int 2147483647
51: invokevirtual #9 // Method java/io/PrintStream.println:(I)V
54: return
LineNumberTable:
line 11: 0
line 12: 8
line 13: 16
line 14: 35
line 15: 54
不加 final 的话是在堆中,拿起来慢一点,加了 final 就是在栈里面直接用,性能高一些。
在 web 阶段学习时,设计 Servlet 时为了保证其线程安全,都会有这样的建议,不要为 Servlet 设置成员变量,这种没有任何成员变量的类是线程安全的。
因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为【无状态】。