posted @ 2013-03-21 09:39 ytl 閱讀(321) | 評(píng)論 (0) | 編輯 收藏
淺談java內(nèi)存模型
posted @ 2012-03-01 18:12 ytl 閱讀(991) | 評(píng)論 (0) | 編輯 收藏
ArrayList
關(guān)于Java中的transient,volatile和strictfp關(guān)鍵字 http://www.iteye.com/topic/52957
(1), ArrayList底層使用Object數(shù)據(jù)實(shí)現(xiàn), private transient Object[] elementData;且在使用不帶參數(shù)的方式實(shí)例化時(shí),生成數(shù)組默認(rèn)的長(zhǎng)度是10。
(2), add方法實(shí)現(xiàn)
關(guān)于Java中的transient,volatile和strictfp關(guān)鍵字 http://www.iteye.com/topic/52957
(1), ArrayList底層使用Object數(shù)據(jù)實(shí)現(xiàn), private transient Object[] elementData;且在使用不帶參數(shù)的方式實(shí)例化時(shí),生成數(shù)組默認(rèn)的長(zhǎng)度是10。
(2), add方法實(shí)現(xiàn)
public boolean add(E e) {
//ensureCapacityInternal判斷添加新元素是否需要重新擴(kuò)大數(shù)組的長(zhǎng)度,需要?jiǎng)t擴(kuò)否則不
//ensureCapacityInternal判斷添加新元素是否需要重新擴(kuò)大數(shù)組的長(zhǎng)度,需要?jiǎng)t擴(kuò)否則不
ensureCapacityInternal(size + 1); // 此為JDK7調(diào)用的方法 JDK5里面使用的ensureCapacity方法
elementData[size++] = e; //把對(duì)象插入數(shù)組,同時(shí)把數(shù)組存儲(chǔ)的數(shù)據(jù)長(zhǎng)度size加1
return true;
}
JDK 7中 ensureCapacityInternal實(shí)現(xiàn)
private void ensureCapacityInternal(int minCapacity) {
modCount++;修改次數(shù)
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);//如果需要擴(kuò)大數(shù)組長(zhǎng)度
}
/**
* The maximum size of array to allocate. --申請(qǐng)新數(shù)組最大長(zhǎng)度
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit --如果申請(qǐng)的數(shù)組占用的內(nèi)心大于JVM的限制拋出異常
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//為什么減去8看注釋第2行
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //新申請(qǐng)的長(zhǎng)度為old的3/2倍同時(shí)使用位移運(yùn)算更高效,JDK5中: (oldCapacity *3)/2+1
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) //你懂的
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
//可以申請(qǐng)的最大長(zhǎng)度
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
posted @ 2011-09-24 15:30 ytl| 編輯 收藏