Advertisement
baksatibi

Untitled

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