#! /bin/bash
echo """
package com.example;
public class DisableGC {
static native void acquire(int[] arr);
static native void release(int[] arr);
public static void main(String... args) throws Throwable {
System.loadLibrary(\"disablegc\");
int[] arr = new int[]{1,2};
acquire(arr);
System.out.println(\"[Acquire]\");
for(int i=0;i<1000;i++){
int[] tmp = new int[1024*1024*50];
System.out.println(tmp);
}
System.out.println(\"[Release]\");
release(arr);
}
}
""" > DisableGC.java
$JAVA_HOME/bin/javac -h . DisableGC.java
echo """
#include \"com_example_DisableGC.h\"
static jintArray sink;
JNIEXPORT void JNICALL Java_com_example_DisableGC_acquire
(JNIEnv *env, jclass klass, jintArray arr) {
sink = (jintArray)(*env)->GetPrimitiveArrayCritical(env, arr, 0);
}
JNIEXPORT void JNICALL Java_com_example_DisableGC_release
(JNIEnv *env, jclass klass, jintArray arr){
(*env)->ReleasePrimitiveArrayCritical(env, arr, sink, 0);
}
""" > com_example_DisableGC.c
gcc -I${JAVA_HOME}/include/linux -I${JAVA_HOME}/include -shared com_example_DisableGC.c -o libdisablegc.so
mkdir -p com/example/
mv DisableGC.class com/example/
OPT="-XX:+UseParallelGC -Xlog:gc* -Xmx1g -Xms1g -Djava.library.path="$(pwd)
$JAVA_HOME/bin/java $OPT com.example.DisableGC
小trick,用的是JNI GetPrimitiveArrayCritical/ReleasePrimitiveArrayCritical,底层是GCLocker。跑一下脚本,结果符合预期:
$./disable_gc.sh
[0.007s][info][gc] Using Parallel
[0.007s][info][gc,heap,coops] Heap address: 0x00000000c0000000, size: 1024 MB, Compressed Oops mode: 32-bit
[Acquire]
[I@5fdef03a
[I@3b22cdd0
[I@1e81f4dc
[I@4d591d15
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.example.DisableGC.main(DisableGC.java:15)
[0.535s][info][gc,heap,exit ] Heap
[0.535s][info][gc,heap,exit ] PSYoungGen total 305664K, used 225772K [0x00000000eab00000, 0x0000000100000000, 0x0000000100000000)
[0.535s][info][gc,heap,exit ] eden space 262144K, 86% used [0x00000000eab00000,0x00000000f877b070,0x00000000fab00000)
[0.535s][info][gc,heap,exit ] from space 43520K, 0% used [0x00000000fd580000,0x00000000fd580000,0x0000000100000000)
[0.535s][info][gc,heap,exit ] to space 43520K, 0% used [0x00000000fab00000,0x00000000fab00000,0x00000000fd580000)
[0.535s][info][gc,heap,exit ] ParOldGen total 699392K, used 614400K [0x00000000c0000000, 0x00000000eab00000, 0x00000000eab00000)
[0.535s][info][gc,heap,exit ] object space 699392K, 87% used [0x00000000c0000000,0x00000000e5800030,0x00000000eab00000)
[0.535s][info][gc,heap,exit ] Metaspace used 3807K, capacity 4486K, committed 4864K, reserved 1056768K
[0.535s][info][gc,heap,exit ] class space used 339K, capacity 386K, committed 512K, reserved 1048576K
原文:https://www.cnblogs.com/kelthuzadx/p/14419730.html