Advertisement
baksatibi

Untitled

Jul 19th, 2014
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. package finalizerdemo;
  2.  
  3. public class B
  4. {
  5.     private int index;
  6.     private B other;
  7.  
  8.     public B(int index)
  9.     {
  10.         this.index = index;
  11.     }
  12.  
  13.     public void setOther(B other)
  14.     {
  15.         this.other = other;
  16.     }
  17.  
  18.     @Override
  19.     protected void finalize() throws Throwable
  20.     {
  21.         System.out.print("B(" + index + ")#finalize");
  22.         finalizerAssert(other != null); // the other object must be still available
  23.         finalizerAssert(index + 1 == other.index || index - 1 == other.index);  // the two indexes must be exactly 1 from each other
  24.         System.out.print(" other(" + other.index + ")");
  25.         if(index > other.index)
  26.         {
  27.             System.out.println(" calling other#finalize");
  28.             System.out.print("\t");
  29.             other.finalize();
  30.         }
  31.         other = null;   // just to make sure if we did something wrong, we would get an assertion error
  32.         System.out.println(" finalizer finished");
  33.     }
  34.  
  35.     private static void finalizerAssert(boolean success)
  36.     {
  37.         if(!success)
  38.         {
  39.             new AssertionError().printStackTrace();
  40.             System.exit(1);
  41.         }
  42.     }
  43.  
  44.     public static void main(String[] args)
  45.     {
  46.         for(int i = 0; true; i += 2)
  47.         {
  48.             B a = new B(i);
  49.             B b = new B(i + 1);
  50.             a.setOther(b);
  51.             b.setOther(a);
  52.             System.out.print('.');  // this is just an indicator that GC doesn't run after every iteration
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement