There is now a possibility to write to a temporary file with Appengine Standard:
https://cloud.google.com/appengine/docs/standard/java11/using-temp-files,
enabling you to create a heap dump programatically and save it to a local file. Once you have the file you can send it to Google Cloud Storage, for example, and analyse it from there.
You can use as you mentioned HotSpotDiagnosticMXBean. Here's a code snippet:
final MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
if (memory.getHeapMemoryUsage().getUsed() > 48 * MB) {
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
final HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
final String fileName = "/tmp/heap.hprof";
mxBean.dumpHeap(fileName, true);
final GcsFilename objectId = new GcsFilename("my_bucket", "heap-dump.hprof");
final GcsOutputChannel output = gcs.createOrReplace(objectId, options);
try (final InputStream is = new FileInputStream(fileName);
final OutputStream os = Channels.newOutputStream(output)) {
final byte[] buffer = new byte[65536];
for (int read; (read = is.read(buffer)) > -1; ) {
os.write(buffer, 0, read);
}
}
}