一. HikariCP内建容器
FastList与ConcurrentBag,FastList主要用来存储Statement,ConcurrentBag用来存储Connection相关的IConcurrentBagEntry(用来生成Connection),都在util包下面
二. FastList的使用场景
HikariCP 没有选择使用ArrayList,而是自己实现了List接口
- 当调用Connection.preapreStatement()时,新的PreparedStatement就被加到FastList
- 当调用PreparedStatement.close()时,这个Statement就会从当前List移除并关闭
- 调用 Connection.close()时,任何未明确关闭的Statement语句都会从FastList移除并关闭
三 .FastList 与ArrayList
- get方法没有检查角标越界,当然这个开销极小
// FastList List直接取数组元素
public T get(int index)
{
return elementData[index];
}
// ArrayList会检查角标是否越界
public E get(int index) {
Objects.checkIndex(index, size);
return elementData(index);
}
- remove方法从尾部遍历;add方法是尾部插入,最先插入元素在数组的前面,通常删除的Statement比较靠近尾部,所以这里从尾部开始遍历。
// FastList从尾部遍历,删除
public boolean remove(Object element)
{
for (int index = size - 1; index >= 0; index--) {
if (element == elementData[index]) {
final int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return true;
}
}
return false;
}
// ArrayList从头部遍历 jdk版本 11
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
fastRemove(es, i);
return true;
}
在ProxyStatement#close方法有调用
public final void close() throws SQLException
{
synchronized (this) {
if (isClosed) {
return;
}
isClosed = true;
}
connection.untrackStatement(delegate);
try {
delegate.close();
}
catch (SQLException e) {
throw connection.checkException(e);
}
}
final synchronized void untrackStatement(final Statement statement)
{
openStatements.remove(statement);
}
- 早期的add方法
版本 2.5.1,甚至连数组越界都没有检查,直接赋值,在捕获异常中进行扩容,作者也是将代码精简到了极致,平时开发中不推荐使用异常控制程序。
@Override
public boolean add(T element)
{
try {
elementData[size++] = element;
}
catch (ArrayIndexOutOfBoundsException e) {
// overflow-conscious code
final int oldCapacity = elementData.length;
final int newCapacity = oldCapacity << 1;
@SuppressWarnings("unchecked")
final T[] newElementData = (T[]) Array.newInstance(clazz, newCapacity);
System.arraycopy(elementData, 0, newElementData, 0, oldCapacity);
newElementData[size - 1] = element;
elementData = newElementData;
}
return true;
}
(下面代码版本号为3.4.5)
后期的版本还是把越界检查这一行不是特别消耗性能的代码加上了。
@Override
public boolean add(T element)
{
if (size < elementData.length) {
elementData[size++] = element;
}
else {
// overflow-conscious code
final int oldCapacity = elementData.length;
final int newCapacity = oldCapacity << 1;
@SuppressWarnings("unchecked")
final T[] newElementData = (T[]) Array.newInstance(clazz, newCapacity);
System.arraycopy(elementData, 0, newElementData, 0, oldCapacity);
newElementData[size++] = element;
elementData = newElementData;
}
return true;
FastList代码比较简单,可以看出来FastList并不是线程安全的,主要是用来存储Statement的,@TOC下一篇记录下ConcurrentBag的学习笔记,它又是不是线程安全的呢?