In Previous article, I described how to check the memory usage status in Java application. This time, after understanding the process that uses memory, I would like to measure how much memory each instance actually uses.
There are several libraries that measure Java size, but this time we will use the ** java-sizeof ** library. A library developed by CARROT SEARCH LAB
--Published in Maven Repository. --Supports Java6,7,8.
There are advantages such as. Download the jar file from Maven epository. If you use Maven, put the following in the pom.xml file. For version, specify the version you want to install. This article uses "0.0.5".
<dependency>
<groupId>com.carrotsearch</groupId>
<artifactId>java-sizeof</artifactId>
<version>{version}</version>
</dependency>
Now, I would like to measure the size of memory using the java-sizeof library. Just call the * RamUsageEstimator.sizeOf * function for the instance you want to measure as follows.
import com.carrotsearch.sizeof.RamUsageEstimator;
import java.util.ArrayList;
import java.util.List;
public class JavaSizeofTest
{
public static void main( String[] args )
{
int[] intArray = new int[10];
List<Integer> intList = new ArrayList<Integer>(10);
for(int i = 0 ; i < 10 ; i++){
intArray[i] = i;
intList.add(i);
}
System.out.println("intArray size(byte) -> " + RamUsageEstimator.sizeOf(intArray));
System.out.println("intList size(byte) -> " + RamUsageEstimator.sizeOf(intList));
}
}
intArray size(byte) -> 56
intList size(byte) -> 240
I got the size of the instance.
You can also measure the memory of your own class instance using the above method. You can recursively know the size of the sum of the sizes of all member variables.
package so_netmedia.java_sizeof_test;
import com.carrotsearch.sizeof.RamUsageEstimator;
import java.util.ArrayList;
import java.util.List;
public class JavaSizeofTest2
{
static class MyClass{
int[] intArray = new int[10];
List<Integer> intList = new ArrayList<Integer>(10);
public MyClass(){
for(int i = 0 ; i < 10 ; i++){
intArray[i] = i;
intList.add(i);
}
}
}
public static void main( String[] args )
{
MyClass myInstance = new MyClass();
System.out.println("myInstance size(byte) -> " + RamUsageEstimator.sizeOf(myInstance));
}
}
myInstance size(byte) -> 320
It's the sum of the instance sizes, plus the class overhead.
By performing the above memory measurement on an instance that seems to be large in size and outputting a log, it is possible to investigate how much memory is used in which instance. Find out which instances are consuming memory and reduce memory. One last thing to note is that it takes some time to measure the memory of ** large instances. ** Do not forget to control, such as measuring in the Staging environment and skipping in production.
Recommended Posts