java回收機制使用 WeakHashMap

來源:互聯網
上載者:User
package gcmap;public class Element {private String ident;public Element(String id) {ident = id;}@Overridepublic String toString() {return ident;}@Overridepublic int hashCode() {return ident.hashCode();}@Overridepublic boolean equals(Object r) {return r instanceof Element && ident.equals(((Element) r).ident);}@Overrideprotected void finalize() throws Throwable {System.out.println("Finalizing "+getClass().getSimpleName()+" "+ident);}}

package gcmap;public class Key extends Element{public Key(String id) {super(id);}}

package gcmap;public class Value extends Element{public Value(String id) {super(id);}}

package gcmap;import java.util.Set;import java.util.WeakHashMap;public class CannonicalMapping {public static void main(String[] args) {int size=10;if(args.length>0){size=new Integer(args[0]);}Key[] keys=new Key[size];WeakHashMap<Key, Value> map=new WeakHashMap<Key, Value>();for(int i=0;i<size;i++){Key k=new Key(Integer.toString(i));Value v=new Value(Integer.toString(i));if(i%3==0){keys[i]=k;}map.put(k, v);}System.gc();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}Set<Key> _keys=map.keySet();for(Key key:_keys){System.out.println("key :"+key+";value :"+map.get(key));}}}

輸出結果:

Finalizing Key 8
Finalizing Key 7
Finalizing Key 5
Finalizing Key 4
Finalizing Key 2
Finalizing Key 1
`````````````````````````````````key :9;value :9
`````````````````````````````````key :6;value :6
`````````````````````````````````key :0;value :0
`````````````````````````````````key :3;value :3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.