Java unit testing: how to measure memory footprint for method call

前端 未结 6 1089
梦毁少年i
梦毁少年i 2020-12-05 04:36

Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can\'t lead to out-of-memo

6条回答
  •  渐次进展
    2020-12-05 05:01

    Here is a sample code to run memory usage in a separate thread. Since the GC can be triggered anytime when the process is running, this will record memory usage every second and report out the maximum memory used.

    The runnable is the actual process that needs measuring, and runTimeSecs is the expected time the process will run. This is to ensure the thread calculating memory does not terminate before the actual process.

    public void recordMemoryUsage(Runnable runnable, int runTimeSecs) {
        try {
            CompletableFuture mainProcessFuture = CompletableFuture.runAsync(runnable);
            CompletableFuture memUsageFuture = CompletableFuture.runAsync(() -> {
    
    
                long mem = 0;
                for (int cnt = 0; cnt < runTimeSecs; cnt++) {
                    long memUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                    mem = memUsed > mem ? memUsed : mem;
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                ;
                System.out.println("Max memory used (gb): " + mem/1000000000D);
            });
    
            CompletableFuture allOf = CompletableFuture.allOf(mainProcessFuture, memUsageFuture);
            allOf.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题