Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package finalizerdemo;
- public class B
- {
- private int index;
- private B other;
- public B(int index)
- {
- this.index = index;
- }
- public void setOther(B other)
- {
- this.other = other;
- }
- @Override
- protected void finalize() throws Throwable
- {
- System.out.print("B(" + index + ")#finalize");
- finalizerAssert(other != null); // the other object must be still available
- finalizerAssert(index + 1 == other.index || index - 1 == other.index); // the two indexes must be exactly 1 from each other
- System.out.print(" other(" + other.index + ")");
- if(index > other.index)
- {
- System.out.println(" calling other#finalize");
- System.out.print("\t");
- other.finalize();
- }
- other = null; // just to make sure if we did something wrong, we would get an assertion error
- System.out.println(" finalizer finished");
- }
- private static void finalizerAssert(boolean success)
- {
- if(!success)
- {
- new AssertionError().printStackTrace();
- System.exit(1);
- }
- }
- public static void main(String[] args)
- {
- for(int i = 0; true; i += 2)
- {
- B a = new B(i);
- B b = new B(i + 1);
- a.setOther(b);
- b.setOther(a);
- System.out.print('.'); // this is just an indicator that GC doesn't run after every iteration
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement