1 /*
   2  * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.io.File;
  25 import java.io.FileDescriptor;
  26 import java.io.FileNotFoundException;
  27 import java.io.RandomAccessFile;
  28 import java.lang.management.ManagementFactory;
  29 import java.lang.management.OperatingSystemMXBean;
  30 import java.lang.ref.Cleaner;
  31 import java.lang.ref.Reference;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;
  34 import java.lang.reflect.Field;
  35 import java.util.HashSet;
  36 
  37 import com.sun.management.UnixOperatingSystemMXBean;
  38 
  39 /**
  40  * @test
  41  * @bug 8080225
  42  * @modules java.base/java.io:open
  43  * @summary Test to ensure that an unclosed and unreferenced RandomAccessFile closes the fd
  44  * @run main/othervm UnreferencedRAFClosesFd
  45  */
  46 public class UnreferencedRAFClosesFd {
  47 
  48     static final String FILE_NAME = "empty.txt";
  49 
  50     /* standalone interface */
  51     public static void main(String argv[]) throws Exception {
  52 
  53         File inFile= new File(System.getProperty("test.dir", "."), FILE_NAME);
  54         inFile.createNewFile();
  55         inFile.deleteOnExit();
  56 
  57         long fdCount0 = getFdCount();
  58         System.out.printf("initial count of open file descriptors: %d%n", fdCount0);
  59 
  60         String name = inFile.getPath();
  61         RandomAccessFile raf;
  62         try {
  63             // raf is explicitly *not* closed to allow cleaner to work
  64             raf = new RandomAccessFile(name, "rw");
  65         } catch (FileNotFoundException e) {
  66             System.out.println("Unexpected exception " + e);
  67             throw(e);
  68         }
  69         FileDescriptor fd = raf.getFD();
  70 
  71         Field fdField = FileDescriptor.class.getDeclaredField("cleanup");
  72         fdField.setAccessible(true);
  73         Cleaner.Cleanable cleanup = (Cleaner.Cleanable)fdField.get(fd);
  74 
  75         // Prepare to wait for FOS, FD, Cleanup to be reclaimed
  76         ReferenceQueue<Object> queue = new ReferenceQueue<>();
  77         HashSet<Reference<?>> pending = new HashSet<>(3);
  78         pending.add(new WeakReference<>(cleanup, queue));
  79         pending.add(new WeakReference<>(raf, queue));
  80         pending.add(new WeakReference<>(fd, queue));
  81 
  82         Reference<?> r;
  83         while (((r = queue.remove(10L)) != null)
  84                 || !pending.isEmpty()) {
  85             System.out.printf("r: %s, pending: %d%n", r, pending.size());
  86             if (r != null) {
  87                 pending.remove(r);
  88             } else {
  89                 cleanup = null;
  90                 raf = null;
  91                 fd = null;
  92                 System.gc();  // attempt to reclaim the RAF, cleanup, and fd
  93             }
  94         }
  95 
  96         // Keep these variables in scope as gc roots
  97         Reference.reachabilityFence(cleanup);
  98         Reference.reachabilityFence(fd);
  99         Reference.reachabilityFence(raf);
 100         Reference.reachabilityFence(pending);
 101 
 102         // Check the final count of open file descriptors
 103         long fdCount = getFdCount();
 104         System.out.printf("final count of open file descriptors: %d%n", fdCount);
 105         if (fdCount != fdCount0) {
 106             throw new AssertionError("raw fd count wrong: expected: " + fdCount0
 107                     + ", actual: " + fdCount);
 108         }
 109     }
 110 
 111 
 112     // Get the count of open file descriptors, or -1 if not available
 113     private static long getFdCount() {
 114         OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
 115         return  (mxBean instanceof UnixOperatingSystemMXBean)
 116                 ? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount()
 117                 : -1L;
 118     }
 119 }