Code Fragment-對於一些資料類中經常使用的使用Cache儲存起來。

來源:互聯網
上載者:User

在Java的api中,對於Integer的cache了-127~128的資料。

在方法valuesOf()中,實現如下

public static Integer valueOf(int i) {assert IntegerCache.high >= 127;if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}

Cache資料的兩種時機:

  • 使用的時候,用到的時候先從cache裡取,有直接取,沒有建立,然後放入cache裡。

    • 一些大的資料類,建立和使用成本都很高,使用懶漢式載入策略。
  • 載入的時候自動建立
    • 資料本身比較小,構造的成本比較小,可以使用餓漢式載入,即在static 代碼塊裡完成了初始化工作。

Integer的餓漢式實現:

private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by property//...cache = new Integer[(high - low) + 1];int j = low;for (int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);}private IntegerCache() {}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.