gpt4 book ai didi

java - 计算对象的 'weight',howto

转载 作者:行者123 更新时间:2023-12-02 11:22:15 27 4
gpt4 key购买 nike

Possible Duplicate:
In Java, what is the best way to determine the size of an object?

假设您有一个数据结构,允许您向其中添加数据,例如列表:

List<KeyValuePair>

当系统的客户端实际添加内容时...在某些时候,JVM 将耗尽内存,这只是何时发生的问题。最好定期将包含此列表的对象保存到磁盘和 gc其余的。

使用Java,是否可以估计一个对象现在占用了多少内存?

最佳答案

您正在寻找java.lang.instrument.Instrumentation.getObjectSize(Object object)

文档:

Returns an implementation-specific approximation of the amount of storage consumed by the specified object. The result may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29

但是为了能够使用它:

The only way to access an instance of the Instrumentation interface is for the JVM to be launched in a way that indicates the agent class - see the package specification. The Instrumentation instance is passed to the premain method of the agent class. Once an agent acquires the Instrumentation instance, the agent may call methods on the instance at any time.

良好的实现示例: http://www.javalobby.org/java/forums/t19309.html

关于java - 计算对象的 'weight',howto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11252249/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com