计算java对象的内存占用
代码引用自:https://blog.csdn.net/antony9118/article/details/54317637 感谢博主分享:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; /**
* This class contains object info generated by ClassIntrospector tool
*/
public class ObjectInfo {
/** Field name */
public final String name;
/** Field type name */
public final String type;
/** Field data formatted as string */
public final String contents;
/** Field offset from the start of parent object */
public final int offset;
/** Memory occupied by this field */
public final int length;
/** Offset of the first cell in the array */
public final int arrayBase;
/** Size of a cell in the array */
public final int arrayElementSize;
/** Memory occupied by underlying array (shallow), if this is array type */
public final int arraySize;
/** This object fields */
public final List<ObjectInfo> children; public ObjectInfo(String name, String type, String contents, int offset, int length, int arraySize,
int arrayBase, int arrayElementSize) {
this.name = name;
this.type = type;
this.contents = contents;
this.offset = offset;
this.length = length;
this.arraySize = arraySize;
this.arrayBase = arrayBase;
this.arrayElementSize = arrayElementSize;
children = new ArrayList<ObjectInfo>(1);
} public void addChild(final ObjectInfo info) {
if (info != null) {
children.add(info);
}
} /**
* Get the full amount of memory occupied by a given object. This value may be slightly less than
* an actual value because we don't worry about memory alignment - possible padding after the last object field.
*
* The result is equal to the last field offset + last field length + all array sizes + all child objects deep sizes
*
* @return Deep object size
*/
public long getDeepSize() {
//return length + arraySize + getUnderlyingSize( arraySize != 0 );
return addPaddingSize(arraySize + getUnderlyingSize(arraySize != 0));
} long size = 0; private long getUnderlyingSize(final boolean isArray) {
//long size = 0;
for (final ObjectInfo child : children)
size += child.arraySize + child.getUnderlyingSize(child.arraySize != 0);
if (!isArray && !children.isEmpty()) {
int tempSize = children.get(children.size() - 1).offset + children.get(children.size() - 1).length;
size += addPaddingSize(tempSize);
} return size;
} private static final class OffsetComparator implements Comparator<ObjectInfo> {
@Override
public int compare(final ObjectInfo o1, final ObjectInfo o2) {
return o1.offset - o2.offset; //safe because offsets are small non-negative numbers
}
} //sort all children by their offset
public void sort() {
Collections.sort(children, new OffsetComparator());
} @Override
public String toString() {
final StringBuilder sb = new StringBuilder();
toStringHelper(sb, 0);
return sb.toString();
} private void toStringHelper(final StringBuilder sb, final int depth) {
depth(sb, depth).append("name=").append(name).append(", type=").append(type)
.append(", contents=").append(contents).append(", offset=").append(offset)
.append(", length=").append(length);
if (arraySize > 0) {
sb.append(", arrayBase=").append(arrayBase);
sb.append(", arrayElemSize=").append(arrayElementSize);
sb.append(", arraySize=").append(arraySize);
}
for (final ObjectInfo child : children) {
sb.append('\n');
child.toStringHelper(sb, depth + 1);
}
} private StringBuilder depth(final StringBuilder sb, final int depth) {
for (int i = 0; i < depth; ++i)
sb.append("\t");
return sb;
} private long addPaddingSize(long size) {
if (size % 8 != 0) {
return (size / 8 + 1) * 8;
}
return size;
} }
ObjectInfo
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map; import sun.misc.Unsafe; /**
* This class could be used for any object contents/memory layout printing.
*/
public class ClassIntrospector { private static final Unsafe unsafe;
/** Size of any Object reference */
private static final int objectRefSize;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null); objectRefSize = unsafe.arrayIndexScale(Object[].class);
} catch (Exception e) {
throw new RuntimeException(e);
}
} /** Sizes of all primitive values */
private static final Map<Class, Integer> primitiveSizes; static {
primitiveSizes = new HashMap<Class, Integer>(10);
primitiveSizes.put(byte.class, 1);
primitiveSizes.put(char.class, 2);
primitiveSizes.put(int.class, 4);
primitiveSizes.put(long.class, 8);
primitiveSizes.put(float.class, 4);
primitiveSizes.put(double.class, 8);
primitiveSizes.put(boolean.class, 1);
} /**
* Get object information for any Java object. Do not pass primitives to
* this method because they will boxed and the information you will get will
* be related to a boxed version of your value.
*
* @param obj
* Object to introspect
* @return Object info
* @throws IllegalAccessException
*/
public ObjectInfo introspect(final Object obj)
throws IllegalAccessException {
try {
return introspect(obj, null);
} finally { // clean visited cache before returning in order to make
// this object reusable
m_visited.clear();
}
} // we need to keep track of already visited objects in order to support
// cycles in the object graphs
private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>(
100); private ObjectInfo introspect(final Object obj, final Field fld)
throws IllegalAccessException {
// use Field type only if the field contains null. In this case we will
// at least know what's expected to be
// stored in this field. Otherwise, if a field has interface type, we
// won't see what's really stored in it.
// Besides, we should be careful about primitives, because they are
// passed as boxed values in this method
// (first arg is object) - for them we should still rely on the field
// type.
boolean isPrimitive = fld != null && fld.getType().isPrimitive();
boolean isRecursive = false; // will be set to true if we have already
// seen this object
if (!isPrimitive) {
if (m_visited.containsKey(obj)) {
isRecursive = true;
}
m_visited.put(obj, true);
} final Class type = (fld == null || (obj != null && !isPrimitive)) ? obj
.getClass() : fld.getType();
int arraySize = 0;
int baseOffset = 0;
int indexScale = 0;
if (type.isArray() && obj != null) {
baseOffset = unsafe.arrayBaseOffset(type);
indexScale = unsafe.arrayIndexScale(type);
arraySize = baseOffset + indexScale * Array.getLength(obj);
} final ObjectInfo root;
if (fld == null) {
root = new ObjectInfo("", type.getCanonicalName(), getContents(obj,
type), 0, getShallowSize(type), arraySize, baseOffset,
indexScale);
} else {
final int offset = (int) unsafe.objectFieldOffset(fld);
root = new ObjectInfo(fld.getName(), type.getCanonicalName(),
getContents(obj, type), offset, getShallowSize(type),
arraySize, baseOffset, indexScale);
} if (!isRecursive && obj != null) {
if (isObjectArray(type)) {
// introspect object arrays
final Object[] ar = (Object[]) obj;
for (final Object item : ar)
if (item != null) {
root.addChild(introspect(item, null));
}
} else {
for (final Field field : getAllFields(type)) {
if ((field.getModifiers() & Modifier.STATIC) != 0) {
continue;
}
field.setAccessible(true);
root.addChild(introspect(field.get(obj), field));
}
}
} root.sort(); // sort by offset
return root;
} // get all fields for this class, including all superclasses fields
private static List<Field> getAllFields(final Class type) {
if (type.isPrimitive()) {
return Collections.emptyList();
}
Class cur = type;
final List<Field> res = new ArrayList<Field>(10);
while (true) {
Collections.addAll(res, cur.getDeclaredFields());
if (cur == Object.class) {
break;
}
cur = cur.getSuperclass();
}
return res;
} // check if it is an array of objects. I suspect there must be a more
// API-friendly way to make this check.
private static boolean isObjectArray(final Class type) {
if (!type.isArray()) {
return false;
}
if (type == byte[].class || type == boolean[].class
|| type == char[].class || type == short[].class
|| type == int[].class || type == long[].class
|| type == float[].class || type == double[].class) {
return false;
}
return true;
} // advanced toString logic
private static String getContents(final Object val, final Class type) {
if (val == null) {
return "null";
}
if (type.isArray()) {
if (type == byte[].class) {
return Arrays.toString((byte[]) val);
} else if (type == boolean[].class) {
return Arrays.toString((boolean[]) val);
} else if (type == char[].class) {
return Arrays.toString((char[]) val);
} else if (type == short[].class) {
return Arrays.toString((short[]) val);
} else if (type == int[].class) {
return Arrays.toString((int[]) val);
} else if (type == long[].class) {
return Arrays.toString((long[]) val);
} else if (type == float[].class) {
return Arrays.toString((float[]) val);
} else if (type == double[].class) {
return Arrays.toString((double[]) val);
} else {
return Arrays.toString((Object[]) val);
}
}
return val.toString();
} // obtain a shallow size of a field of given class (primitive or object
// reference size)
private static int getShallowSize(final Class type) {
if (type.isPrimitive()) {
final Integer res = primitiveSizes.get(type);
return res != null ? res : 0;
} else {
return objectRefSize;
}
}
}
ClassIntrospector
使用:
final ClassIntrospector ci = new ClassIntrospector();
ObjectInfo res;
System.out.println("int:" + ci.introspect(new Integer(2)).getDeepSize());
System.out.println("str3:" + ci.introspect("abcd").getDeepSize()); res = ci.introspect(new ObjectA());
System.out.println("ObjectA:" + res.getDeepSize());
其中 ObjectA:
private static class ObjectA {
String str; //
int i1; //
byte b1; //
byte b2; //
int i2; //
byte b3; //
ObjectB obj; //
}
private static class ObjectB {
}
计算java对象的内存占用的更多相关文章
- 计算Java对象内存大小
摘要 本文以如何计算Java对象占用内存大小为切入点,在讨论计算Java对象占用堆内存大小的方法的基础上,详细讨论了Java对象头格式并结合JDK源码对对象头中的协议字段做了介绍,涉及内存模型.锁原理 ...
- java对象的内存布局(二):利用sun.misc.Unsafe获取类字段的偏移地址和读取字段的值
在上一篇文章中.我们列出了计算java对象大小的几个结论以及jol工具的使用,jol工具的源代码有兴趣的能够去看下.如今我们利用JDK中的sun.misc.Unsafe来计算下字段的偏移地址,一则验证 ...
- java对象在内存的大小
前言 一直以来,对java对象大小的概念停留在基础数据类型,比如byte占1字节,int占4字节,long占8字节等,但是一个对象包含的内存空间肯定不只有这些. 假设有类A和B,当new A()或者n ...
- 如何准确计算Java对象的大小
如何准确计算Java对象的大小 原创文章,转载请注明:博客园aprogramer 原文链接:如何准确计算Java对象的大小 有时,我们需要知道Java对象到底占用多少内存,有人通过连续调用两 ...
- 两种计算Java对象大小的方法
之前想研究一下unsafe类,碰巧在网上看到了这篇文章,觉得写得很好,就转载过来.原文出处是: http://blog.csdn.net/iter_zc/article/details/4182271 ...
- linux Java项目CPU内存占用高故障排查
linux Java项目CPU内存占用高故障排查 top -Hp 进程号 显示进程中每个线程信息,配合jstack定位java线程运行情况 # 线程详情 jstack 线程PID # 查看堆内存中的对 ...
- Java对象的内存模型(一)
前言 新人一枚,刚刚入门编程不久,各方面都在学习当中,博文有什么错误的地方,希望我们可以多多交流! 最近,在开发App后台过程中,需要将项目部署到云服务器上.而云服务器的内存大小却只有1G.要如何做到 ...
- Java对象的内存布局
对象的内存布局 平时用java编写程序,你了解java对象的内存布局么? 在HotSpot虚拟机中,对象在内存中存储的布局可以分为3块区域: 对象头 实例数据 对齐填充 对象头 对象头包括两部分信息: ...
- JVM总结-java对象的内存布局
在 Java 程序中,我们拥有多种新建对象的方式.除了最为常见的 new 语句之外,我们还可以通过反射机制.Object.clone 方法.反序列化以及 Unsafe.allocateInstance ...
随机推荐
- 2017 Multi-University Training Contest - Team 2——HDU6045&&HDU6047&&HDU6055
讲一下这场多校赛里面比较简单的三个题 HDU6045 Is Derek lying? 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6045 题意:有 ...
- 购物车删除商品,总价变化 innerHTML = ''并没有删除节点,内容仍存在
w元素的上的下. function deleteLi(tmpId) { //document.getElementById(tmpId).innerHTML = ''; var wdel = docu ...
- Macbook pro 13" compile Apollo 2.5
STEPS: 0. Install Homebrew 1. Install 'Docker for Mac 18.03+',配置CPUs (n个CPUs,Bazel开n个线程编译), Memory ...
- sigmoid & softmax、cross-entropy、relu
sigmoid函数由于其自身特点,容易造成几个问题 1.当sigmoid在输出层时容易造成loss较大时学习速度慢的情况(或者说是代价函数学习速度衰退问题) 原因:神经网络的学习方式是通过求代价函数对 ...
- icomoon.io生成字体图标
1. 准备svg图片 2. 打开icomoon选择icomoon App 3. import icons 上传本地的svg图片 4. 点击选中以后点击generate fonts形成字体图标 5. p ...
- 对android的认识
1.混乱的返回逻辑 看过Android Design的都知道,在Android上存在有back和up两套导航逻辑,一个控制应用间导航,一个控制应用内导航. 现在的问题就是这两种导航的方式,Google ...
- LVS-DR 配置测试
LVS Lvs体系结构 Lvs工作模式(3种) NAT-网络地址转换模式 当用户请求到达调度器时,调度器将请求报文的目标地址(即虚拟IP地址)改写成选定的Real Server地址,同时报文的目标端口 ...
- 浅析Spring AOP
在正常的业务流程中,往往存在着一些业务逻辑,例如安全审计.日志管理,它们存在于每一个业务中,然而却和实际的业务逻辑没有太强的关联关系. 图1 这些逻辑我们称为横切逻辑.如果把横切的逻辑代码写在业务代码 ...
- 执行Java脚本firefox启动成功,不运行test方法,且提示NullPointerException
在ideal中新建maven项目,将录制好的Java脚本文件,直接复制到项目中,添加相关的依赖脚本. 代码不报错之后,运行录制好的Java脚本,启动了firefox之后,不执行test方法,报错Nul ...
- pytorch rnn 2
import torch import torch.nn as nn import numpy as np import torch.optim as optim class RNN(nn.Modul ...