jdk

Форк
0
/
TestStressG1Uncommit.java 
148 строк · 5.6 Кб
1
/*
2
 * Copyright (c) 2020, 2023, 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
package gc.stress;
25

26
/*
27
 * @test TestStressUncommit
28
 * @key stress
29
 * @summary Stress uncommitting by allocating and releasing memory
30
 * @requires vm.gc.G1
31
 * @library /test/lib
32
 * @modules java.base/jdk.internal.misc
33
 * @run driver/timeout=1300 gc.stress.TestStressG1Uncommit
34
 */
35

36
import java.lang.management.ManagementFactory;
37
import java.lang.management.MemoryMXBean;
38
import java.time.Duration;
39
import java.time.Instant;
40
import java.util.ArrayList;
41
import java.util.Collections;
42
import java.util.LinkedList;
43
import java.util.concurrent.ConcurrentLinkedQueue;
44
import java.util.concurrent.CountDownLatch;
45
import java.util.concurrent.ExecutorService;
46
import java.util.concurrent.Executors;
47
import java.util.concurrent.TimeUnit;
48
import com.sun.management.ThreadMXBean;
49

50
import jdk.test.lib.Asserts;
51
import jdk.test.lib.process.ProcessTools;
52
import jdk.test.lib.process.OutputAnalyzer;
53

54
public class TestStressG1Uncommit {
55
    public static void main(String[] args) throws Exception {
56
        ArrayList<String> options = new ArrayList<>();
57
        Collections.addAll(options,
58
            "-Xlog:gc,gc+heap+region=debug",
59
            "-XX:+UseG1GC",
60
            StressUncommit.class.getName()
61
        );
62
        OutputAnalyzer output = ProcessTools.executeLimitedTestJava(options);
63
        output.shouldHaveExitValue(0);
64
        output.shouldMatch("Uncommit regions");
65
        output.outputTo(System.out);
66
    }
67
}
68

69
class StressUncommit {
70
    private static final long M = 1024 * 1024;
71
    private static final long G = 1024 * M;
72
    private static final Instant StartTime = Instant.now();
73

74
    private static final ThreadMXBean threadBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
75
    private static final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
76
    private static ConcurrentLinkedQueue<Object> globalKeepAlive;
77

78
    public static void main(String args[]) throws InterruptedException {
79
        // Leave 20% head room to try to avoid Full GCs.
80
        long allocationSize = (long) (Runtime.getRuntime().maxMemory() * 0.8);
81

82
        // Figure out suitable number of workers (~1 per gig).
83
        int gigsOfAllocation = (int) Math.ceil((double) allocationSize / G);
84
        int numWorkers = Math.min(gigsOfAllocation, Runtime.getRuntime().availableProcessors());
85
        long workerAllocation = allocationSize / numWorkers;
86

87
        log("Using " + numWorkers + " workers, each allocating: ~" + (workerAllocation / M) + "M");
88
        ExecutorService workers = Executors.newFixedThreadPool(numWorkers);
89
        try {
90
            int iteration = 1;
91
            // Run for 60 seconds.
92
            while (uptime() < 60) {
93
                log("Interation: " + iteration++);
94
                globalKeepAlive = new ConcurrentLinkedQueue<>();
95
                // Submit work to executor.
96
                CountDownLatch workersRunning = new CountDownLatch(numWorkers);
97
                for (int j = 0; j < numWorkers; j++) {
98
                    // Submit worker task.
99
                    workers.submit(() -> {
100
                    allocateToLimit(workerAllocation);
101
                    workersRunning.countDown();
102
                    });
103
                }
104

105
                // Wait for tasks to complete.
106
                workersRunning.await();
107

108
                // Clear the reference holding all task allocations alive.
109
                globalKeepAlive = null;
110

111
                // Do a GC that should shrink the heap.
112
                long committedBefore = memoryBean.getHeapMemoryUsage().getCommitted();
113
                System.gc();
114
                long committedAfter = memoryBean.getHeapMemoryUsage().getCommitted();
115
                Asserts.assertLessThan(committedAfter, committedBefore);
116
            }
117
        } finally {
118
            workers.shutdown();
119
            workers.awaitTermination(5, TimeUnit.SECONDS);
120
        }
121
    }
122

123
    private static void allocateToLimit(long limit) {
124
        var localKeepAlive = new LinkedList<byte[]>();
125

126
        long currentAllocation = threadBean.getCurrentThreadAllocatedBytes();
127
        long allocationLimit = currentAllocation + limit;
128

129
        while (currentAllocation < allocationLimit) {
130
            // Check roughly every megabyte.
131
            for (long j = 0 ; j < 1000; j++) {
132
            localKeepAlive.add(new byte[1024]);
133
            }
134
            currentAllocation = threadBean.getCurrentThreadAllocatedBytes();
135
        }
136

137
        // Add to globalKeepAlive for realease by main thread.
138
        globalKeepAlive.add(localKeepAlive);
139
    }
140

141
    private static long uptime() {
142
        return Duration.between(StartTime, Instant.now()).getSeconds();
143
    }
144

145
    private static void log(String text) {
146
        System.out.println(uptime() + "s: " + text);
147
    }
148
}
149

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.