差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

Both sides previous revision 前次修改
下次修改
前次修改
下次修改 Both sides next revision
java:basic:string_intern [2015/04/27 18:39]
tony [Reference]
java:basic:string_intern [2015/04/27 18:44]
tony [Problem]
行 13: 行 13:
 } }
 </​code>​ </​code>​
-最常見的法是在method上增加synchronized,+最常見的法是在method上增加synchronized,
 <code java> <code java>
 public synchronized ​ Object getCache(String key){ public synchronized ​ Object getCache(String key){
行 37: 行 37:
 } }
 </​code>​ </​code>​
-但對沒使用過的東西,我無法放100萬個心下來,所以稍微google了這method的資訊。赫然發現,許多的人都不推使用String intern()。觀看intern裡面的實做,最後會呼叫到JVM的native code,因此這實做是綁在JVM上的。詳細可以看[[http://​java-performance.info/​string-intern-in-java-6-7-8/​|這篇]],還包含了效能測試結果。\\+但對沒使用過的東西,我無法放100萬個心下來,所以稍微google了這method的資訊。赫然發現,許多的人都不推使用String intern()。觀看intern裡面的實做,最後會呼叫到JVM的native code,因此這實做是綁在JVM上的。詳細可以看[[http://​java-performance.info/​string-intern-in-java-6-7-8/​|這篇]],還包含了效能測試結果。\\ 
 +\\
 總結裡面的重點是:​\\ 總結裡面的重點是:​\\
   - intern建立了一個String Pool。   - intern建立了一個String Pool。
行 43: 行 44:
   - Java7與8 Pool存在Heap中,效能會受GC與預設pool size影響。   - Java7與8 Pool存在Heap中,效能會受GC與預設pool size影響。
   - 要用intern就是要去tune參數。   - 要用intern就是要去tune參數。
-裡面也提到自行實做此String poolgoogle guava也做了這樣的東西:​+如果嫌麻煩不想tune JVM參數,裡面也提到自行實做此String pool。而google guava也做了這樣的東西:​
 <code java> <code java>
 private Interner<​String>​ mStringInterer = Interners.newWeakInterner();​ private Interner<​String>​ mStringInterer = Interners.newWeakInterner();​
行 53: 行 54:
 } }
 </​code>​ </​code>​
 +它是thread-safe的,你也可以根據自己的需求選擇要使用Weak Reference還是Strong Reference。
 ===== Reference ===== ===== Reference =====
   * [[http://​www.javaworld.com/​article/​2077568/​learn-java/​java-tip-67--lazy-instantiation.html|lazy-instantiation]]   * [[http://​www.javaworld.com/​article/​2077568/​learn-java/​java-tip-67--lazy-instantiation.html|lazy-instantiation]]