import com.yourkit.api.MemorySnapshot;
import com.yourkit.api.controller.v2.Controller;

import java.io.File;

/**
 * Note: this class uses the snapshot API {@code com.yourkit.api.MemorySnapshot}
 * which requires Java 11 or newer.
 */
public class ApiDemo2 {
  public static void main(final String[] args) throws Exception {
    // Create the controller to profile the application itself.
    // To profile another application use the builder's methods host() and port() instead of self().
    final Controller controller = Controller.newBuilder().self().build();

    final String snapshotFilePath = controller.captureMemorySnapshot();
    System.out.println("Own memory snapshot captured: " + snapshotFilePath);

    // Load snapshot for analysis
    System.out.println("Loading the captured snapshot...");
    final MemorySnapshot snapshot = new MemorySnapshot(new File(snapshotFilePath));

    // Print some statistics. See "Set description language" in the Help for detail.

    final String classesDescription = "<objects class=\"java.lang.Class\"/>";
    final String objectsDescription = "<objects class=\"java.lang.Object\"/>";
    final String stringsDescription = "<objects class=\"java.lang.String\"/>";
    final String stringRetentionDescription = "<retained-objects>" + stringsDescription + "</retained-objects>";

    final int KB = 1024;

    System.out.println();
    System.out.println("Class count: " + snapshot.getObjectCount(classesDescription));
    System.out.println("Object count: " + snapshot.getObjectCount(objectsDescription));
    System.out.println("String count: " + snapshot.getObjectCount(stringsDescription));
    System.out.println("Size of all objects: " + snapshot.getShallowSize(objectsDescription) / KB + " KB");
    System.out.println("Shallow size of all strings: " + snapshot.getShallowSize(stringsDescription) / KB + " KB");
    System.out.println("Retained size of all strings: " + snapshot.getShallowSize(stringRetentionDescription) / KB + " KB");
  }
}
