File: TimSortStackSize2.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (218 lines) | stat: -rw-r--r-- 8,150 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*
 * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
 * 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.
 */

/*
 * @test
 * @bug 8072909
 * @summary Test TimSort stack size on big arrays
 * @key intermittent
 * @library /lib/testlibrary /test/lib
 * @modules java.management
 *          java.base/jdk.internal
 * @build jdk.testlibrary.*
 * @build TimSortStackSize2
 * @run driver ClassFileInstaller sun.hotspot.WhiteBox
 *                                sun.hotspot.WhiteBox$WhiteBoxPermission
 * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
 *     -XX:+WhiteBoxAPI TimSortStackSize2
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import jdk.testlibrary.Utils;
import sun.hotspot.WhiteBox;

public class TimSortStackSize2 {

    public static void main(String[] args) {
        if ( args == null || args.length == 0 ){
            startMeWithArgs();
        } else {
            doTestOfTwoTimSorts(Integer.parseInt(args[0]));
        }
    }

    private static void startMeWithArgs(){
        /*
         * big tests not for regular execution on all platforms:
         * run main/othervm -Xmx8g TimSortStackSize2 1073741824
         * run main/othervm -Xmx16g TimSortStackSize2 2147483644
         */
        try {
            Boolean compressedOops = WhiteBox.getWhiteBox()
                                             .getBooleanVMFlag("UseCompressedOops");
            long memory = (compressedOops == null || compressedOops) ? 385 : 770;
            final String xmsValue = "-Xms" +     memory + "m";
            final String xmxValue = "-Xmx" + 2 * memory + "m";

            System.out.printf("compressedOops: %s; Test will be started with \"%s %s\"%n",
                              compressedOops, xmsValue, xmxValue);
            OutputAnalyzer output = ProcessTools.executeTestJava(xmsValue,
                                                                 xmxValue,
                                                                 "TimSortStackSize2",
                                                                 "67108864");
            System.out.println(output.getOutput());
            output.shouldHaveExitValue(0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static void doTestOfTwoTimSorts(final int lengthOfTest){
        boolean passed = doTest("TimSort", lengthOfTest,
            (Integer [] a) -> Arrays.sort(a));
        passed = doTest("ComparableTimSort", lengthOfTest, (Integer [] a) ->
            Arrays.sort(a, (Object first, Object second) -> {
                return ((Comparable<Object>)first).compareTo(second);
            }))
            && passed;
        if ( !passed ){
            throw new RuntimeException();
        }
    }

    private static boolean doTest(final String msg, final int lengthOfTest,
                                  final  Consumer<Integer[]> c){
        Integer [] a = null;
        try {
            a = new TimSortStackSize2(lengthOfTest).createArray();
            long begin = System.nanoTime();
            c.accept(a);
            long end = System.nanoTime();
            System.out.println(msg + " OK. Time: " + (end - begin) + "ns");
        } catch (ArrayIndexOutOfBoundsException e){
            System.out.println(msg + " broken:");
            e.printStackTrace();
            return false;
        } finally {
            a = null;
        }
        return true;
    }

    private static final int MIN_MERGE = 32;
    private final int minRun;
    private final int length;
    private final List<Long> runs = new ArrayList<Long>();

    public TimSortStackSize2(final int len) {
        this.length = len;
        minRun = minRunLength(len);
        fillRunsJDKWorstCase();
    }

    private static int minRunLength(int n) {
        assert n >= 0;
        int r = 0;      // Becomes 1 if any 1 bits are shifted off
        while (n >= MIN_MERGE) {
            r |= (n & 1);
            n >>= 1;
        }
        return n + r;
    }

    /**
     * Adds a sequence x_1, ..., x_n of run lengths to <code>runs</code> such that:<br>
     * 1. X = x_1 + ... + x_n <br>
     * 2. x_j >= minRun for all j <br>
     * 3. x_1 + ... + x_{j-2}  <  x_j  <  x_1 + ... + x_{j-1} for all j <br>
     * These conditions guarantee that TimSort merges all x_j's one by one
     * (resulting in X) using only merges on the second-to-last element.
     * @param X  The sum of the sequence that should be added to runs.
     */
    private void generateJDKWrongElem(long X) {
        for(long newTotal; X >= 2 * minRun + 1; X = newTotal) {
            //Default strategy
            newTotal = X / 2 + 1;
            //Specialized strategies
            if(3 * minRun + 3 <= X && X <= 4*minRun+1) {
                // add x_1=MIN+1, x_2=MIN, x_3=X-newTotal  to runs
                newTotal = 2 * minRun + 1;
            } else if (5 * minRun + 5 <= X && X <= 6 * minRun + 5) {
                // add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=X-newTotal  to runs
                newTotal = 3 * minRun + 3;
            } else if (8 * minRun + 9 <= X && X <= 10 * minRun + 9) {
                // add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=2MIN+2, x_5=X-newTotal  to runs
                newTotal = 5 * minRun + 5;
            } else if (13 * minRun + 15 <= X && X <= 16 * minRun + 17) {
                // add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=2MIN+2, x_5=3MIN+4, x_6=X-newTotal  to runs
                newTotal = 8 * minRun + 9;
            }
            runs.add(0, X - newTotal);
        }
        runs.add(0, X);
    }

    /**
     * Fills <code>runs</code> with a sequence of run lengths of the form<br>
     * Y_n     x_{n,1}   x_{n,2}   ... x_{n,l_n} <br>
     * Y_{n-1} x_{n-1,1} x_{n-1,2} ... x_{n-1,l_{n-1}} <br>
     * ... <br>
     * Y_1     x_{1,1}   x_{1,2}   ... x_{1,l_1}<br>
     * The Y_i's are chosen to satisfy the invariant throughout execution,
     * but the x_{i,j}'s are merged (by <code>TimSort.mergeCollapse</code>)
     * into an X_i that violates the invariant.
     * X is the sum of all run lengths that will be added to <code>runs</code>.
     */
    private void fillRunsJDKWorstCase() {
        long runningTotal = 0;
        long Y = minRun + 4;
        long X = minRun;

        while (runningTotal + Y + X <= length) {
            runningTotal += X + Y;
            generateJDKWrongElem(X);
            runs.add(0, Y);

            // X_{i+1} = Y_i + x_{i,1} + 1, since runs.get(1) = x_{i,1}
            X = Y + runs.get(1) + 1;

            // Y_{i+1} = X_{i+1} + Y_i + 1
            Y += X + 1;
        }

        if (runningTotal + X <= length) {
            runningTotal += X;
            generateJDKWrongElem(X);
        }

        runs.add(length - runningTotal);
    }

    private Integer [] createArray() {
        Integer [] a = new Integer[length];
        Arrays.fill(a, 0);
        int endRun = -1;
        for (long len : runs) {
            a[endRun += len] = 1;
        }
        a[length - 1] = 0;
        return a;
    }

}