// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.UnsupportedEncodingException;
import java.util.Map;

import dk.vajhoej.record.RecordException;

import static dk.vajhoej.vms.call.lib.VMSCodes.*;
import static dk.vajhoej.vms.call.lib.VMSStatus.*;
import static dk.vajhoej.vms.call.lib.SYS.*;

public class MemAna {
    private static void printStatus(String lbl) throws UnsupportedEncodingException, RecordException {
        System.gc();
        Result<Map<Integer,Object>> res = SYS$GETJPIW(0, new int[] { JPI$_WSSIZE,
                                                                     JPI$_PPGCNT, JPI$_GPGCNT,
                                                                     JPI$_PAGFILCNT, JPI$_PGFLQUOTA });
        if(res.getStatus() == SS$_NORMAL) {
            System.out.printf("%-20s: heap = %8d, wssize = %8d, pgcnt = %8d, usedpgfl = %8d\n",
                              lbl,
                              (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 512,
                              res.getResult().get(JPI$_WSSIZE),                          
                              (int)(Integer)res.getResult().get(JPI$_PPGCNT) + (int)(Integer)res.getResult().get(JPI$_GPGCNT),
                              (int)(Integer)res.getResult().get(JPI$_PGFLQUOTA) - (int)(Integer)res.getResult().get(JPI$_PAGFILCNT));
        } else {
            System.out.printf("sys$getjpiw returned: %d\n", res.getStatus());
        }
    }
    public static void main(String[] args) throws Exception {
        printStatus("Start");
        for(int i = 0; i < 3; i++) {
            byte[] b1 = new byte[100000 * 512];
            printStatus("New 100000 pages");
            byte[] b2 = new byte[100000 * 512];
            printStatus("New 100000 pages");
            byte[] b3 = new byte[100000 * 512];
            printStatus("New 100000 pages");
            byte[] b4 = new byte[100000 * 512];
            printStatus("New 100000 pages");
            byte[] b5 = new byte[100000 * 512];
            printStatus("New 100000 pages");
            if(b1[0] != 0 || b2[0] != 0 || b3[0] != 0 || b4[0] != 0 || b5[0] != 0) throw new RuntimeException("Ooops");
            b1 = null;
            b2 = null;
            b3 = null;
            b4 = null;
            b5 = null;
            printStatus("Back");
        }
    }
}
