Skip to content

Instantly share code, notes, and snippets.

@tomty89
Created November 27, 2021 02:04
Show Gist options
  • Save tomty89/a64caba831558954b09050d2dfd9e848 to your computer and use it in GitHub Desktop.
Save tomty89/a64caba831558954b09050d2dfd9e848 to your computer and use it in GitHub Desktop.
An attempt to differentiate object instance and reference
class Meh {
@Override
protected void finalize() {
try {
super.finalize();
} catch (Throwable e) {
;
}
System.out.println("\"" + this + "\" " + "destroyed");
}
}
public class Huh {
public static void main(String[] args) {
Meh first_ref = new Meh();
Meh second_ref0 = new Meh();
Meh second_ref1 = second_ref0; // duplicate the reference
System.out.println(first_ref);
System.out.println(second_ref0); // same "value", same output
System.out.println(second_ref1); // same "value", same output
System.out.println(new Meh()); // let's call it third
System.gc(); // third is queued to get destroyed
second_ref0 = null; // second is still referred by second_ref1
System.gc(); // hence none is queued to get destroyed
first_ref = null;
System.gc(); // first is queued to get destroyed
second_ref1 = null; // second is no longer referred at all now
System.gc(); // second is queued to get destoryed
while (true)
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment