- Java 11 and 12:New Features
- Mala Gupta
- 169字
- 2021-07-02 12:27:06
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.
推薦閱讀
- AngularJS入門與進階
- Cocos2D-X權威指南(第2版)
- Git Version Control Cookbook
- DevOps with Kubernetes
- Practical Data Science Cookbook(Second Edition)
- VSTO開發入門教程
- Linux網絡程序設計:基于龍芯平臺
- 你必須知道的204個Visual C++開發問題
- Quarkus實踐指南:構建新一代的Kubernetes原生Java微服務
- Java設計模式及實踐
- SAS數據統計分析與編程實踐
- Linux操作系統基礎案例教程
- Python算法從菜鳥到達人
- BIM概論及Revit精講
- Java高并發核心編程(卷1):NIO、Netty、Redis、ZooKeeper