Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.ref.PhantomReference;
- import java.lang.ref.Reference;
- import java.lang.ref.ReferenceQueue;
- public class GCTest {
- @SuppressWarnings("ClassNamingConvention")
- static class A {
- private String myName;
- A(String myName) {
- this.myName = myName;
- }
- }
- public static void main(String[] args) throws InterruptedException {
- //noinspection LocalCanBeFinal
- A a1 = new A("a1");
- //noinspection LocalCanBeFinal
- A a2 = new A("a2");
- final ReferenceQueue<A> collectedReferenced = new ReferenceQueue<>();
- final PhantomReference<A> phantomA1 = new PhantomReference<>(a1, collectedReferenced);
- final PhantomReference<A> phantomA2 = new PhantomReference<>(a2, collectedReferenced);
- System.out.println("a1 -> " + phantomA1);
- System.out.println("a2 -> " + phantomA2);
- a1 = a2;
- //noinspection CallToSystemGC
- System.gc();
- //noinspection InfiniteLoopStatement
- while (true) {
- final Reference<? extends A> elem = collectedReferenced.remove();
- System.out.println("collected: " + elem.toString());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment