以String类为例
在java中,String
是我们平时用到的最常见的不可变类之一,这里我们以String
类为例,看看不可变类的设计。
在String
类的开头部分如下,我们可以看到String类被final
修饰,同时其成员变量value
也被final
修饰。
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
修饰则保证了该类中方法不能被覆盖,类无法被继承,防止了子类无意间破坏方法的功能
保护性拷贝
由于String中的value
变量是一个引用变量,为了防止有外部引用对其修改,因此其所有引用都需要被String控制,避免对外共享。
以其中的substring()
为例,在返回子字符串对象时,substring
会重新创建一个新的对象,而在其构造方法中,会对原数组进行一次拷贝而不是直接使用原数组。
这种通过创建副本对象来避免共享的手段成为保护性拷贝。
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);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
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);
}
享元模式
保护性拷贝虽然能够避免变量共享,但是如果频繁创建变量,会造成不必要的性能浪费。
定义
英文名:Flyweight Pattern
当需要重用数量有限的同一类对象时,可以使用享元模式。
归类
结构模式
JDK体现
包装类
在JDK中Boolean
、Byte
、Short
、Integer
、Long
、Character
等包装类提供了valueOf()
方法,例如Long
的valueOf()
方法会缓存-128~127之间的类对象,在这个范围内会重用对象,大于这个范围,才会每次创建新的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);
}
注意:
Byte
、Short
、Long
的缓存范围是-128~127Character
的缓存范围是-0~127Integer
的默认缓存范围是-128127,但是它的最大值可以通过虚拟机参数`-Djava.lang.Integer.IntegerCache.high`来调大(如果该值设置的127小,其范围缓存依然为-128127)Boolean
缓存了True和False
其它使用享元模式的类
- String 池
- BigDecimal、BigInteger
使用享元模式实现自定义数据库连接池
- 在连接池初始化时,需要指定连接池大小,并初始化相应的连接
- 为了表示每个连接是否被借出,我们使用原子数组
states
行表示,其中0表示没有被借出,1表示被借出了 - 在借出连接的函数
borrow()
中,需要遍历states
,同时为了防止多线程导致的同步问题,可以使用CAS机制来保护对states
各个元素的修改 - 在归还连接的函数
free()
中,需要先检查连接是否存在于连接池中是否真的存在该连接 - 如果在
borrow()
中遍历完全部元素没有发现可用的连接,任务可以陷入等待状态,直到free()
完成归还连接的操作后再将它们唤醒
public class DiyDatabasePool {
private int size;
private Connection[] connections;
private AtomicIntegerArray states;
public DiyDatabasePool(int size) {
this.size = size;
connections = new Connection[size];
for (int i = 0; i < size; i++) {
connections[i] = new Connection("连接"+i);
}
states = new AtomicIntegerArray(size);
}
/**
* 借出连接
* @return 被借出的连接
*/
public Connection borrow(){
while (true){
for (int i = 0; i < size; i++) {
if (states.get(i)==0&&states.compareAndSet(i,0,1)){
log.info("获取连接:{}",connections[i]);
return connections[i];
}
}
synchronized (this){
try {
log.info("进入等待");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 归还连接
* @param connection 被归还的连接
*/
public void free(Connection connection){
for (int i = 0; i < size; i++) {
if (connections[i] == connection){
states.set(i,0);
synchronized (this){
log.info("归还:{}",connection);
this.notifyAll();
}
break;
}
}
}
}
class Connection{
private String name;
public Connection(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Connection{");
sb.append("name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
下面是测试类,在测试类中,我们创建了一个大小为3的连接池,同时产生了5个连接线程。在每个线程中,当拿到连接后,线程会随机睡眠一段时间,这是为了模仿实际使用连接所用的时间。线程睡眠结束后会归还线程。运行测试代码,其打印日志如下。
[221 ms] [INFO][t-1] i.k.e.c.e.DiyDatabasePool : 获取连接:Connection{name='连接1'}
[221 ms] [INFO][t-4] i.k.e.c.e.DiyDatabasePool : 进入等待
[221 ms] [INFO][t-0] i.k.e.c.e.DiyDatabasePool : 获取连接:Connection{name='连接0'}
[221 ms] [INFO][t-2] i.k.e.c.e.DiyDatabasePool : 获取连接:Connection{name='连接2'}
[224 ms] [INFO][t-3] i.k.e.c.e.DiyDatabasePool : 进入等待
[234 ms] [INFO][t-2] i.k.e.c.e.DiyDatabasePool : 归还:Connection{name='连接2'}
[234 ms] [INFO][t-4] i.k.e.c.e.DiyDatabasePool : 进入等待
[234 ms] [INFO][t-3] i.k.e.c.e.DiyDatabasePool : 获取连接:Connection{name='连接2'}
[273 ms] [INFO][t-3] i.k.e.c.e.DiyDatabasePool : 归还:Connection{name='连接2'}
[273 ms] [INFO][t-4] i.k.e.c.e.DiyDatabasePool : 获取连接:Connection{name='连接2'}
[292 ms] [INFO][t-1] i.k.e.c.e.DiyDatabasePool : 归还:Connection{name='连接1'}
[584 ms] [INFO][t-4] i.k.e.c.e.DiyDatabasePool : 归还:Connection{name='连接2'}
[1163 ms] [INFO][t-0] i.k.e.c.e.DiyDatabasePool : 归还:Connection{name='连接0'}
注意:
- CAS适合于短时间完成的任务,因为执行CAS操作会不断占用CPU
- 对于连接池、线程池这种可能时间较长的任务,不适合让CAS一直空转
该连接池可以继续完善:
- 连接池的动态增长于搜索
- 连接保活(可用性检测)
- 等待超时处理
- 分布式hash
final原理
设置final变量的原理
当虚拟机给final变量也会通过putfield指令来完成,并在这条指令之后加入写屏障,保证其它线程读到它的值是不会在出现0的情况。
获取final变量的原理
当虚拟机给final变量是,字节码指令会直接转变为获取对应的常量。
无状态类
无状态类指没有成员变量的类,他们因为没有保存状态,因此是线程安全的。