JOL: View Java Object Layout, Size Tool

 

It is not easy to write, please indicate when reprinting (http://shihlei.iteye.com/blog/2407693)!

I. Overview

Recently, I plan to cache data in memory. The amount of data is 1.3 trillion and will increase. It is a common monitoring need to understand the size of the space occupied by these data.

In a conventional way, the approximate heap occupancy of the cached object can be estimated manually according to the size of the Java basic data type and content size, but the trouble is not yet accurate.

OpenJDK, which provides the JOL package, can help us calculate the size of an object at runtime, which is a very good tool

 

Official website: http://openjdk.java.net/projects/code-tools/jol/

Positioning: Analyze the size and distribution of objects in the JVM

rely:

 

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>put-the-version-here</version>
</dependency>

 

Second use

 1) Prepare a map for testing the results of JOL Api

static Object generate() {
        Map<String, Object> map = new HashMap<>();
        map.put("a", new Integer(1));
        map.put("b", "b");
        map.put("c", new Date());

        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
        return map;
    }

 

 2) Several commonly used methods

(1) View the internal information of the object:  ClassLayout.parseInstance(obj).toPrintable()

 

 

(2) View the external information of the object: including the referenced object: GraphLayout.parseInstance(obj).toPrintable()



 

(3) View the total size of the object occupied space: GraphLayout.parseInstance(obj).totalSize()

 

Three complete Demos

 

package x.demo.java;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;

public class JolDemo {

    static Object generate() {
        Map<String, Object> map = new HashMap<>();
        map.put("a", new Integer(1));
        map.put("b", "b");
        map.put("c", new Date());

        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
        return map;
    }

    static void print(String message) {
        System.out.println(message);
        System.out.println("-------------------------");
    }

    public static void main(String[] args) {
        Object obj = generate();

        //View the internal information of the object
        print(ClassLayout.parseInstance(obj).toPrintable());

        //View the external information of the object
        print(GraphLayout.parseInstance(obj).toPrintable());

        //Get the total size of the object
        print("size : " + GraphLayout.parseInstance(obj).totalSize());
    }
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326116870&siteId=291194637