在 Java 中,确定对象大小的最佳方法是什么? [英] In Java, what is the best way to determine the size of an object?

查看:32
本文介绍了在 Java 中,确定对象大小的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以读取包含成堆数据行的 CSV 文件.我根据数据类型向用户提供了行数的摘要,但我想确保我不会读入太多行数据并导致 OutOfMemoryErrors.每行转换为一个对象.有没有一种简单的方法可以以编程方式找出该对象的大小?是否有定义 VM 的基本类型和对象引用有多大的引用?

I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a VM?

现在,我的代码表示最多读取 32,000 行,但我还希望代码表示读取尽可能多的行,直到我使用 32MB 的记忆.也许这是一个不同的问题,但我仍然想知道.

Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory. Maybe that is a different question, but I'd still like to know.

推荐答案

您可以使用 java.lang.instrument.

You can use the java.lang.instrument package.

编译并把这个类放在一个 JAR 中:

Compile and put this class in a JAR:

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

将以下内容添加到您的 MANIFEST.MF:

Add the following to your MANIFEST.MF:

Premain-Class: ObjectSizeFetcher

使用 getObjectSize() 方法:

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}

调用方式:

java -javaagent:ObjectSizeFetcherAgent.jar C

这篇关于在 Java 中,确定对象大小的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆