Advertisement
baksatibi

Untitled

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