Class Memory

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12 package org.locationtech.jts.util;
13  
14 /**
15  * Utility functions to report JVM memory usage.
16  * 
17  * @author mbdavis
18  *
19  */
20 public class Memory 
21 {
22     public static long used()
23     {
24         Runtime runtime = Runtime.getRuntime ();
25         return runtime.totalMemory() - runtime.freeMemory();
26     }
27     
28     public static String usedString()
29     {
30         return format(used());
31     }
32     
33     public static long free()
34     {
35         Runtime runtime = Runtime.getRuntime ();
36         return runtime.freeMemory();
37     }
38     
39     public static String freeString()
40     {
41         return format(free());
42     }
43     
44     public static long total()
45     {
46         Runtime runtime = Runtime.getRuntime ();
47         return runtime.totalMemory();
48     }
49     
50     public static String totalString()
51     {
52         return format(total());
53     }
54     
55     public static String usedTotalString()
56     {
57         return "Used: " + usedString() 
58         + "   Total: " + totalString();
59     }
60     
61     public static String allString()
62     {
63         return "Used: " + usedString() 
64         + "   Free: " + freeString()
65         + "   Total: " + totalString();
66     }
67     
68     public static final double KB = 1024;
69     public static final double MB = 1048576;
70     public static final double GB = 1073741824;
71  
72     public static String format(long mem)
73     {
74         if (mem < 2 * KB)
75             return mem + " bytes";
76         if (mem < 2 * MB)
77             return round(mem / KB) + " KB";
78         if (mem < 2 * GB)
79             return round(mem / MB) + " MB";
80         return round(mem / GB) + " GB";
81     }
82     
83     public static double round(double d)
84     {
85         return Math.ceil(d * 100) / 100;
86     }
87 }
88