HikariCP源碼分析之FastList

HikariCP源碼分析之FastList



 

FastList是一個List接口的精簡實現,只實現了接口中必要的幾個方法。JDK ArrayList每次調用get()方法時都會進行rangeCheck檢查索引是否越界,FastList的實現中去除了這一檢查,只要保證索引合法那麼rangeCheck就成爲了不必要的計算開銷(當然開銷極小)。此外,HikariCP使用List來保存打開的Statement,當Statement關閉或Connection關閉時需要將對應的Statement從List中移除。通常情況下,同一個Connection創建了多個Statement時,後打開的Statement會先關閉。ArrayList的remove(Object)方法是從頭開始遍歷數組,而FastList是從數組的尾部開始遍歷,因此更爲高效。

簡而言之就是 自定義數組類型(FastList)代替ArrayList:避免每次get()調用都要進行range check,避免調用remove()時的從頭到尾的掃描。

源碼分析

java.util.ArrayList

 

[AppleScript] 純文本查看 複製代碼
1
2
3
4
5
6
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable</code>
 
com.zaxxer.hikari.util.FastList
 
<code class="">public final class FastList<T> implements List<T>, RandomAccess, Serializable

 

我們先看一下java.util.ArrayList的get方法

 

[AppleScript] 純文本查看 複製代碼
01
02
03
04
05
06
07
08
09
10
11
/**
    * Returns the element at the specified position in this list.
    *
    * @param  index index of the element to return
    * @return the element at the specified position in this list
    * @throws IndexOutOfBoundsException {@inheritDoc}
    */
   public E get(int index) {
       rangeCheck(index);
       return elementData(index);
   }

 

我們可以看到每次get的時候都會進行rangeCheck

 

[AppleScript] 純文本查看 複製代碼
01
02
03
04
05
06
07
08
09
10
/**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

 

我們對比一下com.zaxxer.hikari.util.FastList的get方法,可以看到取消了rangeCheck,一定程度下追求了極致

 

[AppleScript] 純文本查看 複製代碼
01
02
03
04
05
06
07
08
09
10
/**
 * Get the element at the specified index.
 *
 * @param index the index of the element to get
 * @return the element, or ArrayIndexOutOfBounds is thrown if the index is invalid
 */
@Override
public T get(int index) {
   return elementData[index];
}

 

我們再來看一下ArrayList的remove(Object)方法
[AppleScript] 純文本查看 複製代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
再對比看一下FastList的remove(Object方法)
[AppleScript] 純文本查看 複製代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
/**
    * This remove method is most efficient when the element being removed
    * is the last element.  Equality is identity based, not equals() based.
    * Only the first matching element is removed.
    *
    * @param element the element to remove
    */
   @Override
   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;
   }
好了,今天的文章就是這麼簡短,最後附一下FastList的源碼,內容真的是十分精簡的。
[AppleScript] 純文本查看 複製代碼
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright (C) 2013, 2014 Brett Wooldridge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * [url=http://www.apache.org/licenses/LICENSE-2.0]http://www.apache.org/licenses/LICENSE-2.0[/url]
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zaxxer.hikari.util;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/**
 * Fast list without range checking.
 *
 * @author Brett Wooldridge
 */
public final class FastList<T> implements List<T>, RandomAccess, Serializable {
   private static final long serialVersionUID = -4598088075242913858L;
   private final Class<?> clazz;
   private T[] elementData;
   private int size;
   /**
    * Construct a FastList with a default size of 32.
    * @param clazz the Class stored in the collection
    */
   @SuppressWarnings("unchecked")
   public FastList(Class<?> clazz) {
      this.elementData = (T[]) Array.newInstance(clazz, 32);
      this.clazz = clazz;
   }
   /**
    * Construct a FastList with a specified size.
    * @param clazz the Class stored in the collection
    * @param capacity the initial size of the FastList
    */
   @SuppressWarnings("unchecked")
   public FastList(Class<?> clazz, int capacity) {
      this.elementData = (T[]) Array.newInstance(clazz, capacity);
      this.clazz = clazz;
   }
   /**
    * Add an element to the tail of the FastList.
    *
    * @param element the element to add
    */
   @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;
   }
   /**
    * Get the element at the specified index.
    *
    * @param index the index of the element to get
    * @return the element, or ArrayIndexOutOfBounds is thrown if the index is invalid
    */
   @Override
   public T get(int index) {
      return elementData[index];
   }
   /**
    * Remove the last element from the list.  No bound check is performed, so if this
    * method is called on an empty list and ArrayIndexOutOfBounds exception will be
    * thrown.
    *
    * @return the last element of the list
    */
   public T removeLast() {
      T element = elementData[--size];
      elementData[size] = null;
      return element;
   }
   /**
    * This remove method is most efficient when the element being removed
    * is the last element.  Equality is identity based, not equals() based.
    * Only the first matching element is removed.
    *
    * @param element the element to remove
    */
   @Override
   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;
   }
   /**
    * Clear the FastList.
    */
   @Override
   public void clear() {
      for (int i = 0; i < size; i++) {
         elementData[i] = null;
      }
      size = 0;
   }
   /**
    * Get the current number of elements in the FastList.
    *
    * @return the number of current elements
    */
   @Override
   public int size() {
      return size;
   }
   /** {@inheritDoc} */
   @Override
   public boolean isEmpty() {
      return size == 0;
   }
   /** {@inheritDoc} */
   @Override
   public T set(int index, T element) {
      T old = elementData[index];
      elementData[index] = element;
      return old;
   }
   /** {@inheritDoc} */
   @Override
   public T remove(int index) {
      if (size == 0) {
         return null;
      }
      final T old = elementData[index];
      final int numMoved = size - index - 1;
      if (numMoved > 0) {
         System.arraycopy(elementData, index + 1, elementData, index, numMoved);
      }
      elementData[--size] = null;
      return old;
   }
   /** {@inheritDoc} */
   @Override
   public boolean contains(Object o) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public Iterator<T> iterator() {
      return new Iterator<T>() {
         private int index;
         @Override
         public boolean hasNext() {
            return index < size;
         }
         @Override
         public T next() {
            if (index < size) {
               return elementData[index++];
            }
            throw new NoSuchElementException("No more elements in FastList");
         }
      };
   }
   /** {@inheritDoc} */
   @Override
   public Object[] toArray()
   {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public <E> E[] toArray(E[] a)
   {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean containsAll(Collection<?> c) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean addAll(Collection<? extends T> c) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean addAll(int index, Collection<? extends T> c) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean removeAll(Collection<?> c) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean retainAll(Collection<?> c) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public void add(int index, T element) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public int indexOf(Object o) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public int lastIndexOf(Object o) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public ListIterator<T> listIterator() {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public ListIterator<T> listIterator(int index) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public List<T> subList(int fromIndex, int toIndex) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public Object clone() {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public void forEach(Consumer<? super T> action) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public Spliterator<T> spliterator() {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public boolean removeIf(Predicate<? super T> filter) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public void replaceAll(UnaryOperator<T> operator) {
      throw new UnsupportedOperationException();
   }
   /** {@inheritDoc} */
   @Override
   public void sort(Comparator<? super T> c) {
      throw new UnsupportedOperationException();
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章