Различия
Здесь показаны различия между двумя версиями данной страницы.
Предыдущая версия справа и слева Предыдущая версия | |||
dev:java:lang:weakrefs [2012/08/04 18:45] jamis7005 |
dev:java:lang:weakrefs [2012/08/04 20:34] (текущий) jamis7005 |
||
---|---|---|---|
Строка 2: | Строка 2: | ||
<code java> | <code java> | ||
- | + | class TestA { | |
- | class TheStrong { | + | private Object link; |
- | public Object link; | + | |
public Object getLink(){ return link; } | public Object getLink(){ return link; } | ||
- | public void print(Object newlink){ | + | public void setLinkAndPrint(Object newlink){ |
link = newlink; | link = newlink; | ||
- | System.out.println("TheStrong: my link =" + getLink()); | + | print(); |
+ | } | ||
+ | |||
+ | public void print(){ | ||
+ | Runtime r = Runtime.getRuntime(); | ||
+ | r.gc(); | ||
+ | System.out.println(getClass().getName() + ": link =" + getLink()); | ||
} | } | ||
} | } | ||
- | class TheWeak { | + | class TestB { |
- | public WeakReference<Object> link; | + | private WeakReference<Object> link; |
public Object getLink(){ return link.get(); } | public Object getLink(){ return link.get(); } | ||
- | public void print(Object newlink){ | + | public void setLinkAndPrint(Object newlink){ |
link = new WeakReference<>( newlink ); | link = new WeakReference<>( newlink ); | ||
- | System.out.println("TheWeak: my link =" + getLink()); | + | print(); |
+ | } | ||
+ | |||
+ | public void print(){ | ||
+ | Runtime r = Runtime.getRuntime(); | ||
+ | r.gc(); | ||
+ | System.out.println(getClass().getName() + ": link =" + getLink()); | ||
} | } | ||
} | } | ||
- | public class Test { | + | public class TestWeakRef { |
- | public static void main(String[] args) throws IOException { | + | public static void main(String[] args) { |
- | TheStrong thestrong = new TheStrong(); | + | TestA a = new TestA(); |
- | thestrong.print(Arrays.asList(4,5,6)); | + | a.setLinkAndPrint(Arrays.asList(4,5,6)); |
+ | a.print(); | ||
- | TheWeak theweak = new TheWeak(); | + | TestB b = new TestB(); |
- | theweak.print(Arrays.asList(1,2,3)); | + | b.setLinkAndPrint(Arrays.asList(1,2,3)); |
- | + | b.print(); | |
- | Runtime r = Runtime.getRuntime(); | + | |
- | r.gc(); | + | |
- | + | ||
- | System.out.println("TheWeak: its link=" + theweak.getLink()); | + | |
- | System.out.println("TheStrong: its link=" + thestrong.getLink()); | + | |
} | } | ||
} | } | ||
- | |||
- | |||
</code> | </code> | ||
Строка 47: | Строка 52: | ||
Result: | Result: | ||
<code> | <code> | ||
- | TheWeak: my link =[1, 2, 3] | + | promauto.batchext.TestA: link =[4, 5, 6] |
- | TheStrong: my link =[4, 5, 6] | + | promauto.batchext.TestA: link =[4, 5, 6] |
- | TheWeak: its link=null | + | promauto.batchext.TestB: link =[1, 2, 3] |
- | TheStrong: its link=[4, 5, 6] | + | promauto.batchext.TestB: link =null |
</code> | </code> | ||