官术网_书友最值得收藏!

Sample code

The following sample code allocates an image array of size 999999 and loads images to it. Then, the code retrieves the image bytes and stores them to a byte array of size 999999.

On a heap size of 3,044 MB and region size of 1 MB, this code will force full G1 GC and eventually shut down the JVM with OutOfMemoryError:

import java.io.*; 
import java.awt.image.BufferedImage; 
import javax.imageio.ImageIO; 
public class TriggerG1FullGC { 
    final BufferedImage[] images = new BufferedImage[999999]; 
    final byte[][] imgByte = new byte[999999][]; 
 
    public TriggerG1FullGC() throws Exception { 
        for (int i = 0; i < 999999; i++) { 
            images[i] = ImageIO.read(new File("img.jpg")); 
        } 
        System.out.println("Images read"); 
 
        for (int i = 0; i < 999999; i++) { 
            ByteArrayOutputStream baos=new ByteArrayOutputStream(); 
            ImageIO.write(images[i], "jpg", baos ); 
            imgByte[i] = baos.toByteArray(); 
        } 
        System.out.println("Bytes read"); 
    } 
    public static void main(String... args) throws Exception { 
        new TriggerG1FullGC(); 
    } 
} 

You can execute the preceding code using the following command:

    > java -Xlog:gc* -Xlog:gc*:myG1log.log TriggerG1FullGC 

 

The preceding code will output GC logs to the console (by courtesy of -Xlog:gc*). It will also store the log to the myG1log.log file. The code (as we expected) will fail with OutOfMemoryError. Let's examine the contents of the GC log file.

Starting with Java 9, G1 is the default GC. So, the preceding code doesn't use any runtime options to specifically use G1.
主站蜘蛛池模板: 大英县| 海阳市| 衡阳县| 汪清县| 平舆县| 沙雅县| 浠水县| 扎囊县| 肥东县| 西林县| 墨玉县| 淮北市| 湘乡市| 南充市| 临泽县| 应用必备| 章丘市| 荔波县| 高台县| 万山特区| 昌宁县| 康马县| 盐津县| 南澳县| 建始县| 遵义县| 泸定县| 登封市| 永康市| 赣榆县| 恭城| 凤冈县| 富裕县| 武城县| 大宁县| 兰州市| 竹溪县| 太仓市| 疏附县| 南开区| 海口市|