TestShrinkAuxiliaryData.java 12.1 KB
Newer Older
1
/*
2
 * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

24
import com.oracle.java.testlibrary.Asserts;
25 26 27 28 29 30 31 32 33 34 35 36 37 38
import com.oracle.java.testlibrary.OutputAnalyzer;
import com.oracle.java.testlibrary.Platform;
import com.oracle.java.testlibrary.ProcessTools;
import com.oracle.java.testlibrary.Utils;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
39 40
import sun.misc.Unsafe; // for ADDRESS_SIZE
import sun.hotspot.WhiteBox;
41 42 43

public class TestShrinkAuxiliaryData {

44 45
    private static final int REGION_SIZE = 1024 * 1024;

46 47 48 49
    private final static String[] initialOpts = new String[]{
        "-XX:MinHeapFreeRatio=10",
        "-XX:MaxHeapFreeRatio=11",
        "-XX:+UseG1GC",
50
        "-XX:G1HeapRegionSize=" + REGION_SIZE,
51
        "-XX:-ExplicitGCInvokesConcurrent",
52 53 54 55
        "-XX:+PrintGCDetails",
        "-XX:+UnlockDiagnosticVMOptions",
        "-XX:+WhiteBoxAPI",
        "-Xbootclasspath/a:.",
56 57
    };

58
    private final int hotCardTableSize;
59

60 61
    protected TestShrinkAuxiliaryData(int hotCardTableSize) {
        this.hotCardTableSize = hotCardTableSize;
62 63 64 65 66 67 68
    }

    protected void test() throws Exception {
        ArrayList<String> vmOpts = new ArrayList();
        Collections.addAll(vmOpts, initialOpts);

        int maxCacheSize = Math.max(0, Math.min(31, getMaxCacheSize()));
69
        if (maxCacheSize < hotCardTableSize) {
70
            System.out.format("Skiping test for %d cache size due max cache size %d",
71
                    hotCardTableSize, maxCacheSize
72 73 74 75 76 77
            );
            return;
        }

        printTestInfo(maxCacheSize);

78
        vmOpts.add("-XX:G1ConcRSLogCacheSize=" + hotCardTableSize);
79
        vmOpts.addAll(Arrays.asList(Utils.getTestJavaOpts()));
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

        // for 32 bits ObjectAlignmentInBytes is not a option
        if (Platform.is32bit()) {
            ArrayList<String> vmOptsWithoutAlign = new ArrayList(vmOpts);
            vmOptsWithoutAlign.add(ShrinkAuxiliaryDataTest.class.getName());
            performTest(vmOptsWithoutAlign);
            return;
        }

        for (int alignment = 3; alignment <= 8; alignment++) {
            ArrayList<String> vmOptsWithAlign = new ArrayList(vmOpts);
            vmOptsWithAlign.add("-XX:ObjectAlignmentInBytes="
                    + (int) Math.pow(2, alignment));
            vmOptsWithAlign.add(ShrinkAuxiliaryDataTest.class.getName());

            performTest(vmOptsWithAlign);
        }
    }

    private void performTest(List<String> opts) throws Exception {
        ProcessBuilder pb
101 102 103
                = ProcessTools.createJavaProcessBuilder(
                        opts.toArray(new String[opts.size()])
                );
104 105

        OutputAnalyzer output = new OutputAnalyzer(pb.start());
106 107
        System.out.println(output.getStdout());
        System.err.println(output.getStderr());
108 109 110 111 112 113 114 115 116 117
        output.shouldHaveExitValue(0);
    }

    private void printTestInfo(int maxCacheSize) {

        DecimalFormat grouped = new DecimalFormat("000,000");
        DecimalFormatSymbols formatSymbols = grouped.getDecimalFormatSymbols();
        formatSymbols.setGroupingSeparator(' ');
        grouped.setDecimalFormatSymbols(formatSymbols);

118 119
        System.out.format(
                "Test will use %s bytes of memory of %s available%n"
120 121 122
                + "Available memory is %s with %d bytes pointer size - can save %s pointers%n"
                + "Max cache size: 2^%d = %s elements%n",
                grouped.format(ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
123 124
                grouped.format(Runtime.getRuntime().maxMemory()),
                grouped.format(Runtime.getRuntime().maxMemory()
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
                Unsafe.ADDRESS_SIZE,
                grouped.format((Runtime.getRuntime().freeMemory()
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest())
                        / Unsafe.ADDRESS_SIZE),
                maxCacheSize,
                grouped.format((int) Math.pow(2, maxCacheSize))
        );
    }

    /**
     * Detects maximum possible size of G1ConcRSLogCacheSize available for
     * current process based on maximum available process memory size
     *
     * @return power of two
     */
    private static int getMaxCacheSize() {
        long availableMemory = Runtime.getRuntime().freeMemory()
                - ShrinkAuxiliaryDataTest.getMemoryUsedByTest() - 1l;
        if (availableMemory <= 0) {
            return 0;
        }
147

148 149 150 151 152 153 154 155
        long availablePointersCount = availableMemory / Unsafe.ADDRESS_SIZE;
        return (63 - (int) Long.numberOfLeadingZeros(availablePointersCount));
    }

    static class ShrinkAuxiliaryDataTest {

        public static void main(String[] args) throws IOException {

156 157 158 159
            ShrinkAuxiliaryDataTest testCase = new ShrinkAuxiliaryDataTest();

            if (!testCase.checkEnvApplicability()) {
                return;
160 161
            }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            testCase.test();
        }

        /**
         * Checks is this environment suitable to run this test
         * - memory is enough to decommit (page size is not big)
         * - RSet cache size is not too big
         *
         * @return true if test could run, false if test should be skipped
         */
        protected boolean checkEnvApplicability() {

            int pageSize = WhiteBox.getWhiteBox().getVMPageSize();
            System.out.println( "Page size = " + pageSize
                    + " region size = " + REGION_SIZE
                    + " aux data ~= " + (REGION_SIZE * 3 / 100));
            // If auxdata size will be less than page size it wouldn't decommit.
            // Auxiliary data size is about ~3.6% of heap size.
            if (pageSize >= REGION_SIZE * 3 / 100) {
                System.out.format("Skipping test for too large page size = %d",
                       pageSize
                );
                return false;
            }

            if (REGION_SIZE * REGIONS_TO_ALLOCATE > Runtime.getRuntime().maxMemory()) {
                System.out.format("Skipping test for too low available memory. "
                        + "Need %d, available %d",
                        REGION_SIZE * REGIONS_TO_ALLOCATE,
                        Runtime.getRuntime().maxMemory()
                );
                return false;
            }

            return true;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        }

        class GarbageObject {

            private final List<byte[]> payload = new ArrayList();
            private final List<GarbageObject> ref = new LinkedList();

            public GarbageObject(int size) {
                payload.add(new byte[size]);
            }

            public void addRef(GarbageObject g) {
                ref.add(g);
            }

            public void mutate() {
                if (!payload.isEmpty() && payload.get(0).length > 0) {
                    payload.get(0)[0] = (byte) (Math.random() * Byte.MAX_VALUE);
                }
            }
        }

        private final List<GarbageObject> garbage = new ArrayList();

221 222 223 224
        public void test() throws IOException {

            MemoryUsage muFull, muFree, muAuxDataFull, muAuxDataFree;
            float auxFull, auxFree;
225 226 227 228 229

            allocate();
            link();
            mutate();

230 231 232 233 234
            muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
            long numUsedRegions = WhiteBox.getWhiteBox().g1NumMaxRegions()
                    - WhiteBox.getWhiteBox().g1NumFreeRegions();
            muAuxDataFull = WhiteBox.getWhiteBox().g1AuxiliaryMemoryUsage();
            auxFull = (float)muAuxDataFull.getUsed() / numUsedRegions;
235

236 237 238
            System.out.format("Full aux data  ratio= %f, regions max= %d, used= %d\n",
                    auxFull, WhiteBox.getWhiteBox().g1NumMaxRegions(), numUsedRegions
            );
239

240
            deallocate();
241
            System.gc();
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

            muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
            muAuxDataFree = WhiteBox.getWhiteBox().g1AuxiliaryMemoryUsage();

            numUsedRegions = WhiteBox.getWhiteBox().g1NumMaxRegions()
                    - WhiteBox.getWhiteBox().g1NumFreeRegions();
            auxFree = (float)muAuxDataFree.getUsed() / numUsedRegions;

            System.out.format("Free aux data ratio= %f, regions max= %d, used= %d\n",
                    auxFree, WhiteBox.getWhiteBox().g1NumMaxRegions(), numUsedRegions
            );

            Asserts.assertLessThanOrEqual(muFree.getCommitted(), muFull.getCommitted(),
                    String.format("heap decommit failed - full > free: %d > %d",
                            muFree.getCommitted(), muFull.getCommitted()
257 258 259
                    )
            );

260 261 262 263 264 265 266 267 268
            System.out.format("State               used   committed\n");
            System.out.format("Full aux data: %10d %10d\n", muAuxDataFull.getUsed(), muAuxDataFull.getCommitted());
            System.out.format("Free aux data: %10d %10d\n", muAuxDataFree.getUsed(), muAuxDataFree.getCommitted());

            // if decommited check that aux data has same ratio
            if (muFree.getCommitted() < muFull.getCommitted()) {
                Asserts.assertLessThanOrEqual(auxFree, auxFull,
                        String.format("auxiliary data decommit failed - full > free: %f > %f",
                                auxFree, auxFull
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
                        )
                );
            }
        }

        private void allocate() {
            for (int r = 0; r < REGIONS_TO_ALLOCATE; r++) {
                for (int i = 0; i < NUM_OBJECTS_PER_REGION; i++) {
                    GarbageObject g = new GarbageObject(REGION_SIZE
                            / NUM_OBJECTS_PER_REGION);
                    garbage.add(g);
                }
            }
        }

        /**
         * Iterate through all allocated objects, and link to objects in another
         * regions
         */
        private void link() {
            for (int ig = 0; ig < garbage.size(); ig++) {
                int regionNumber = ig / NUM_OBJECTS_PER_REGION;

                for (int i = 0; i < NUM_LINKS; i++) {
                    int regionToLink;
                    do {
295
                        regionToLink = (int) (Math.random() * REGIONS_TO_ALLOCATE);
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                    } while (regionToLink == regionNumber);

                    // get random garbage object from random region
                    garbage.get(ig).addRef(garbage.get(regionToLink
                            * NUM_OBJECTS_PER_REGION + (int) (Math.random()
                            * NUM_OBJECTS_PER_REGION)));
                }
            }
        }

        private void mutate() {
            for (int ig = 0; ig < garbage.size(); ig++) {
                garbage.get(ig).mutate();
            }
        }

        private void deallocate() {
            garbage.clear();
            System.gc();
        }

        static long getMemoryUsedByTest() {
            return REGIONS_TO_ALLOCATE * REGION_SIZE;
        }

321
        private static final int REGIONS_TO_ALLOCATE = 100;
322 323 324 325
        private static final int NUM_OBJECTS_PER_REGION = 10;
        private static final int NUM_LINKS = 20; // how many links create for each object
    }
}