1 /*
   2  * Copyright (c) 2014, 2016, 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 /**
  25  * @test TestSoftReferencesBehaviorOnOOME
  26  * @key gc
  27  * @summary Tests that all SoftReferences has been cleared at time of OOM.
  28  * @library /test/lib
  29  * @modules java.base/jdk.internal.misc
  30  *          java.management
  31  * @run main/othervm -Xmx128m TestSoftReferencesBehaviorOnOOME 512 2k
  32  * @run main/othervm -Xmx128m TestSoftReferencesBehaviorOnOOME 128k 256k
  33  * @run main/othervm -Xmx128m TestSoftReferencesBehaviorOnOOME 2k 32k
  34  */
  35 import jdk.test.lib.Utils;
  36 import jdk.test.lib.Asserts;
  37 import java.lang.ref.SoftReference;
  38 import java.util.LinkedList;
  39 import java.util.Random;
  40 
  41 public class TestSoftReferencesBehaviorOnOOME {
  42 
  43     /**
  44      * Test generates a lot of soft references to objects with random payloads.
  45      * Then it provokes OOME and checks that all SoftReferences has been gone
  46      * @param args - [minSize] [maxSize] [freq]
  47      *  where
  48      *  - minSize - min size of random objects
  49      *  - maxSize - max size of random objects
  50      */
  51     public static void main(String[] args) {
  52         long minSize = DEFAULT_MIN_SIZE;
  53         long maxSize = DEFAULT_MAX_SIZE;
  54 
  55         if ( args.length >= 2) {
  56             maxSize = getBytesCount(args[1]);
  57         }
  58 
  59         if ( args.length >= 1) {
  60             minSize = getBytesCount(args[0]);
  61         }
  62 
  63         new TestSoftReferencesBehaviorOnOOME().softReferencesOom(minSize, maxSize);
  64     }
  65 
  66     /**
  67      * Test that all SoftReferences has been cleared at time of OOM.
  68      */
  69     void softReferencesOom(long minSize, long maxSize) {
  70         System.out.format( "minSize = %d, maxSize = %d%n", minSize, maxSize );
  71 
  72         LinkedList<SoftReference> arrSoftRefs = new LinkedList();
  73         staticRef = arrSoftRefs;
  74         LinkedList arrObjects = new LinkedList();
  75         staticRef = arrObjects;
  76 
  77         long multiplier = maxSize - minSize;
  78         long numberOfNotNulledObjects = 0;
  79 
  80         try {
  81 
  82             // Lets allocate as many as we can - taking size of all SoftRerefences
  83             // by minimum. So it can provoke some GC but we surely will allocate enough.
  84             long numSofts = (long) ((0.95 * Runtime.getRuntime().totalMemory()) / minSize);
  85             System.out.println("num Soft: " + numSofts);
  86 
  87             while (numSofts-- > 0) {
  88                 int allocationSize = ((int) (RND_GENERATOR.nextDouble() * multiplier))
  89                             + (int)minSize;
  90                 arrSoftRefs.add(new SoftReference(new byte[allocationSize]));
  91             }
  92 
  93             System.out.println("free: " + Runtime.getRuntime().freeMemory());
  94 
  95             // provoke OOME.
  96             while (true) {
  97                 arrObjects.add(new byte[(int) Runtime.getRuntime().totalMemory()]);
  98             }
  99 
 100         } catch (OutOfMemoryError oome) {
 101 
 102             // Clear allocated ballast, so we don't get another OOM.
 103             staticRef = null;
 104             arrObjects = null;
 105             long oomSoftArraySize = arrSoftRefs.size();
 106 
 107             for (SoftReference sr : arrSoftRefs) {
 108                 Object o = sr.get();
 109 
 110                 if (o != null) {
 111                     numberOfNotNulledObjects++;
 112                 }
 113             }
 114 
 115             // Make sure we clear all refs before we return failure
 116             arrSoftRefs = null;
 117             Asserts.assertFalse(numberOfNotNulledObjects > 0,
 118                     "" + numberOfNotNulledObjects + " out of "
 119                     + oomSoftArraySize + " SoftReferences was not "
 120                     + "null at time of OutOfMemoryError"
 121             );
 122         } finally {
 123             Asserts.assertTrue(arrObjects == null, "OOME hasn't been provoked");
 124             Asserts.assertTrue(arrSoftRefs == null, "OOME hasn't been provoked");
 125         }
 126     }
 127 
 128     private static final long getBytesCount(String arg) {
 129         String postfixes = "kMGT";
 130         long mod = 1;
 131 
 132         if (arg.trim().length() >= 2) {
 133             mod = postfixes.indexOf(arg.trim().charAt(arg.length() - 1));
 134 
 135             if (mod != -1) {
 136                 mod = (long) Math.pow(1024, mod+1);
 137                 arg = arg.substring(0, arg.length() - 1);
 138             } else {
 139                 mod = 1; // 10^0
 140             }
 141         }
 142 
 143         return Long.parseLong(arg) * mod;
 144     }
 145 
 146     private static final Random RND_GENERATOR = Utils.getRandomInstance();
 147     private static final long DEFAULT_MIN_SIZE = 512;
 148     private static final long DEFAULT_MAX_SIZE = 1024;
 149     private static Object staticRef; // to prevent compile optimisations
 150 }