< prev index next >

test/jdk/java/io/FileInputStream/UnreferencedFISClosesFd.java

Print this page
rev 50699 : 8202292: java/io/FileOutputStream/UnreferencedFOSClosesFd.java fails with "raw fd count wrong"


   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 /**
  25  *
  26  * @test
  27  * @modules java.base/java.io:open


  28  * @bug 6524062
  29  * @summary Test to ensure that FIS.finalize() invokes the close() method as per
  30  * the specification.
  31  * @run main/othervm UnreferencedFISClosesFd
  32  */
  33 import java.io.File;
  34 import java.io.FileDescriptor;
  35 import java.io.FileInputStream;
  36 import java.io.FileNotFoundException;
  37 import java.io.IOException;
  38 import java.lang.management.ManagementFactory;
  39 import java.lang.management.OperatingSystemMXBean;
  40 import java.lang.ref.Reference;
  41 import java.lang.ref.ReferenceQueue;
  42 import java.lang.ref.WeakReference;
  43 import java.lang.reflect.Field;
  44 import java.nio.file.Files;
  45 import java.nio.file.Path;
  46 import java.nio.file.Paths;
  47 import java.util.ArrayDeque;
  48 import java.util.HashSet;
  49 import java.util.List;
  50 import java.util.Optional;
  51 import java.util.concurrent.TimeUnit;
  52 import java.util.concurrent.atomic.AtomicInteger;
  53 
  54 import com.sun.management.UnixOperatingSystemMXBean;
  55 


  56 /**
  57  * Tests for FIS unreferenced.
  58  *  - Not subclassed - cleaner cleanup
  59  *  - Subclassed no finalize or close - cleaner cleanup
  60  *  - Subclassed close overridden - AltFinalizer cleanup
  61  *  - Subclasses finalize overridden - cleaner cleanup
  62  *  - Subclasses finalize and close overridden - AltFinalizer cleanup
  63  */
  64 public class UnreferencedFISClosesFd {
  65 
  66     enum CleanupType {
  67         CLOSE,      // Cleanup is handled via calling close
  68         CLEANER}    // Cleanup is handled via Cleaner
  69 
  70     static final String FILE_NAME = "empty.txt";
  71 
  72     /**
  73      * Subclass w/ no overrides; not finalize or close.
  74      * Cleanup should be via the Cleaner (not close).
  75      */


 129             super(name);
 130         }
 131 
 132         @SuppressWarnings({"deprecation","removal"})
 133         protected void finalize() throws IOException {
 134             super.finalize();
 135         }
 136     }
 137 
 138     /**
 139      * Main runs each test case and reports number of failures.
 140      */
 141     public static void main(String argv[]) throws Exception {
 142 
 143         File inFile = new File(System.getProperty("test.dir", "."), FILE_NAME);
 144         inFile.createNewFile();
 145         inFile.deleteOnExit();
 146 
 147         String name = inFile.getPath();
 148 

 149         long fdCount0 = getFdCount();
 150         System.out.printf("initial count of open file descriptors: %d%n", fdCount0);
 151 
 152         int failCount = 0;
 153         failCount += test(new FileInputStream(name), CleanupType.CLEANER);
 154 
 155         failCount += test(new StreamOverrides(name), CleanupType.CLEANER);
 156 
 157         failCount += test(new StreamOverridesClose(name), CleanupType.CLOSE);
 158 
 159         failCount += test(new StreamOverridesFinalize(name), CleanupType.CLEANER);
 160 
 161         failCount += test(new StreamOverridesFinalizeClose(name), CleanupType.CLOSE);
 162 
 163         if (failCount > 0) {
 164             throw new AssertionError("Failed test count: " + failCount);
 165         }
 166 
 167         // Check the final count of open file descriptors
 168         long fdCount = getFdCount();
 169         System.out.printf("final count of open file descriptors: %d%n", fdCount);
 170         if (fdCount != fdCount0) {
 171             listProcFD();
 172             throw new AssertionError("raw fd count wrong: expected: " + fdCount0
 173                     + ", actual: " + fdCount);
 174         }
 175     }
 176 
 177     // Get the count of open file descriptors, or -1 if not available
 178     private static long getFdCount() {
 179         OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
 180         return  (mxBean instanceof UnixOperatingSystemMXBean)
 181                 ? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount()
 182                 : -1L;
 183     }
 184 
 185     private static int test(FileInputStream fis, CleanupType cleanType) throws Exception {
 186 
 187         try {
 188             System.out.printf("%nTesting %s%n", fis.getClass().getName());
 189 
 190             // Prepare to wait for FIS to be reclaimed
 191             ReferenceQueue<Object> queue = new ReferenceQueue<>();
 192             HashSet<Reference<?>> pending = new HashSet<>();
 193             WeakReference<FileInputStream> msWeak = new WeakReference<>(fis, queue);


 256 
 257             // Confirm the correct number of calls to close depending on the cleanup type
 258             switch (cleanType) {
 259                 case CLEANER:
 260                     if (closeCounter != null && closeCounter.get() > 0) {
 261                         throw new RuntimeException("Close should not have been called: count: "
 262                                 + closeCounter);
 263                     }
 264                     break;
 265                 case CLOSE:
 266                     if (closeCounter == null || closeCounter.get() == 0) {
 267                         throw new RuntimeException("Close should have been called: count: 0");
 268                     }
 269                     break;
 270             }
 271         } catch (Exception ex) {
 272             ex.printStackTrace(System.out);
 273             return 1;
 274         }
 275         return 0;
 276     }
 277 
 278     /**
 279      * Method to list the open file descriptors (if supported by the 'lsof' command).
 280      */
 281     static void listProcFD() {
 282         List<String> lsofDirs = List.of("/usr/bin", "/usr/sbin");
 283         Optional<Path> lsof = lsofDirs.stream()
 284                 .map(s -> Paths.get(s, "lsof"))
 285                 .filter(f -> Files.isExecutable(f))
 286                 .findFirst();
 287         lsof.ifPresent(exe -> {
 288             try {
 289                 System.out.printf("Open File Descriptors:%n");
 290                 long pid = ProcessHandle.current().pid();
 291                 ProcessBuilder pb = new ProcessBuilder(exe.toString(), "-p", Integer.toString((int) pid));
 292                 pb.inheritIO();
 293                 Process p = pb.start();
 294                 p.waitFor(10, TimeUnit.SECONDS);
 295             } catch (IOException | InterruptedException ie) {
 296                 ie.printStackTrace();
 297             }
 298         });
 299     }
 300 }


   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 /**
  25  *
  26  * @test
  27  * @modules java.base/java.io:open
  28  * @library /test/lib
  29  * @build jdk.test.lib.util.FileUtils UnreferencedFISClosesFd
  30  * @bug 6524062
  31  * @summary Test to ensure that FIS.finalize() invokes the close() method as per
  32  * the specification.
  33  * @run main/othervm UnreferencedFISClosesFd
  34  */
  35 import java.io.File;
  36 import java.io.FileDescriptor;
  37 import java.io.FileInputStream;
  38 import java.io.FileNotFoundException;
  39 import java.io.IOException;
  40 import java.lang.management.ManagementFactory;
  41 import java.lang.management.OperatingSystemMXBean;
  42 import java.lang.ref.Reference;
  43 import java.lang.ref.ReferenceQueue;
  44 import java.lang.ref.WeakReference;
  45 import java.lang.reflect.Field;

  46 import java.nio.file.Path;

  47 import java.util.ArrayDeque;
  48 import java.util.HashSet;



  49 import java.util.concurrent.atomic.AtomicInteger;
  50 
  51 import com.sun.management.UnixOperatingSystemMXBean;
  52 
  53 import jdk.test.lib.util.FileUtils;
  54 
  55 /**
  56  * Tests for FIS unreferenced.
  57  *  - Not subclassed - cleaner cleanup
  58  *  - Subclassed no finalize or close - cleaner cleanup
  59  *  - Subclassed close overridden - AltFinalizer cleanup
  60  *  - Subclasses finalize overridden - cleaner cleanup
  61  *  - Subclasses finalize and close overridden - AltFinalizer cleanup
  62  */
  63 public class UnreferencedFISClosesFd {
  64 
  65     enum CleanupType {
  66         CLOSE,      // Cleanup is handled via calling close
  67         CLEANER}    // Cleanup is handled via Cleaner
  68 
  69     static final String FILE_NAME = "empty.txt";
  70 
  71     /**
  72      * Subclass w/ no overrides; not finalize or close.
  73      * Cleanup should be via the Cleaner (not close).
  74      */


 128             super(name);
 129         }
 130 
 131         @SuppressWarnings({"deprecation","removal"})
 132         protected void finalize() throws IOException {
 133             super.finalize();
 134         }
 135     }
 136 
 137     /**
 138      * Main runs each test case and reports number of failures.
 139      */
 140     public static void main(String argv[]) throws Exception {
 141 
 142         File inFile = new File(System.getProperty("test.dir", "."), FILE_NAME);
 143         inFile.createNewFile();
 144         inFile.deleteOnExit();
 145 
 146         String name = inFile.getPath();
 147 
 148         FileUtils.listFileDescriptors(System.out);
 149         long fdCount0 = getFdCount();

 150 
 151         int failCount = 0;
 152         failCount += test(new FileInputStream(name), CleanupType.CLEANER);
 153 
 154         failCount += test(new StreamOverrides(name), CleanupType.CLEANER);
 155 
 156         failCount += test(new StreamOverridesClose(name), CleanupType.CLOSE);
 157 
 158         failCount += test(new StreamOverridesFinalize(name), CleanupType.CLEANER);
 159 
 160         failCount += test(new StreamOverridesFinalizeClose(name), CleanupType.CLOSE);
 161 
 162         if (failCount > 0) {
 163             throw new AssertionError("Failed test count: " + failCount);
 164         }
 165 
 166         // Check the final count of open file descriptors
 167         long fdCount = getFdCount();

 168         if (fdCount != fdCount0) {
 169             System.out.printf("initial count of open file descriptors: %d%n", fdCount0);
 170             System.out.printf("final count of open file descriptors: %d%n", fdCount);
 171             FileUtils.listFileDescriptors(System.out);
 172         }
 173     }
 174 
 175     // Get the count of open file descriptors, or -1 if not available
 176     private static long getFdCount() {
 177         OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
 178         return  (mxBean instanceof UnixOperatingSystemMXBean)
 179                 ? ((UnixOperatingSystemMXBean) mxBean).getOpenFileDescriptorCount()
 180                 : -1L;
 181     }
 182 
 183     private static int test(FileInputStream fis, CleanupType cleanType) throws Exception {
 184 
 185         try {
 186             System.out.printf("%nTesting %s%n", fis.getClass().getName());
 187 
 188             // Prepare to wait for FIS to be reclaimed
 189             ReferenceQueue<Object> queue = new ReferenceQueue<>();
 190             HashSet<Reference<?>> pending = new HashSet<>();
 191             WeakReference<FileInputStream> msWeak = new WeakReference<>(fis, queue);


 254 
 255             // Confirm the correct number of calls to close depending on the cleanup type
 256             switch (cleanType) {
 257                 case CLEANER:
 258                     if (closeCounter != null && closeCounter.get() > 0) {
 259                         throw new RuntimeException("Close should not have been called: count: "
 260                                 + closeCounter);
 261                     }
 262                     break;
 263                 case CLOSE:
 264                     if (closeCounter == null || closeCounter.get() == 0) {
 265                         throw new RuntimeException("Close should have been called: count: 0");
 266                     }
 267                     break;
 268             }
 269         } catch (Exception ex) {
 270             ex.printStackTrace(System.out);
 271             return 1;
 272         }
 273         return 0;























 274     }
 275 }
< prev index next >