Why does the Java process memory still increase after calling memory.close?

82 Views Asked by At

After running the following program, the memory occupied by the Java process increased from 83M to 99M. Through monitoring, it was found that the increase was almost 1.4M several times (approximately equal to the size of the bytes array). Memory.close() seems to not work occasionally? In theory, shouldn't the memory size occupied by the Java process be equal to the memory used by the program itself plus the allocated 2M memory?

 public static void main(String[] args) throws IOException {
        File imageFile = new File("test.jpeg");
        BufferedImage image = ImageIO.read(imageFile);
        byte[] bytes = bufferedImageToByteArray(image);
        for (int i = 0; i < 100; i++) {
            Pointer data = new Memory(2 * 1024 * 1024);
            data.write(0, bytes, 0, bytes.length);
            if(data instanceof Memory){
                ((Memory)data).close();
            }
        }
    }

private static byte[] bufferedImageToByteArray(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        byte[] byteArray = new byte[width * height * 3];
        Raster raster = image.getRaster();
        int numBands = raster.getNumBands();
        int index = 0;
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int[] pixel = new int[numBands];
                raster.getPixel(x, y, pixel);
                // Blue
                byteArray[index++] = (byte) (pixel[2] & 0xFF);
                // Green
                byteArray[index++] = (byte) (pixel[1] & 0xFF);
                // Red
                byteArray[index++] = (byte) (pixel[0] & 0xFF);
            }
        }
        return byteArray;
    }

env: jdk 11, jna 5.13

This is the memory utilization curve in a real scenario

  • This is the memory utilization curve in a real scenario,
0

There are 0 best solutions below