All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.sandec.jmemorybuddy.MemoryLeakUtils Maven / Gradle / Ivy

There is a newer version: 0.5.5
Show newest version
package de.sandec.jmemorybuddy;

import com.sun.management.HotSpotDiagnosticMXBean;
import javax.management.MBeanServer;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.function.Consumer;
import java.util.function.Function;

public class MemoryLeakUtils {

    static int steps = 10;
    static int overallTime = 5000;
    static int sleepTime = overallTime / steps;

    public static void createGarbage() {
        LinkedList list = new LinkedList();
        int counter = 0;
        while(counter < 999999) {
            counter += 1;
            list.add(1);
        }
    }

    public static void assertCollectable(WeakReference weakReference) {
        int counter = 0;

        createGarbage();
        System.gc();

        while(counter < steps && weakReference.get() != null) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {}
            counter = counter + 1;
            createGarbage();
            System.gc();
        }

        if(weakReference.get() != null) {
            doHeapDump();
            throw new RuntimeException("Content of Weakreference was not collected. content: " + weakReference.get());
        } else {
            if(counter > steps / 3) {
                int percentageUsed = (int) (counter / steps * 100);
                System.out.println("Warning test seems to be unstable. time used: " + percentageUsed + "%");
            }
        }

    }

    public static void doMemTest(Consumer> f) {
        LinkedList> toCheck = new LinkedList>();

        f.accept((Object elem) -> toCheck.add(new WeakReference(elem)));

        for(WeakReference wRef: toCheck) {
            assertCollectable(wRef);
        }

    }


    public static void doHeapDump() {
        try {
            String dateString = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
            String fileName = "heapdump_jmemb_" + dateString + ".hprof";
            System.out.println("Creating Heapdump at: " + new java.io.File(fileName).getAbsolutePath());
            getHotspotMBean().dumpHeap(fileName, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static HotSpotDiagnosticMXBean getHotspotMBean() throws IOException {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        HotSpotDiagnosticMXBean bean =
                ManagementFactory.newPlatformMXBeanProxy(server,
                        "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
        return bean;
    }


}