计算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 ...
随机推荐
- linux mint19.1解决网易云音乐安装后打不开的问题
安装网易云音乐: sudo dpkg -i 文件路径#文件路径可以直接把刚才下载的软件包拖进终端sudo apt install -f 修复依赖关系 安装后打不开的问题: 1.sudo gedit / ...
- requests和bs4
requests模块,仿造浏览器发送Http请求bs4主要对html或xml格式字符串解析成对象,使用find/find_all查找 text/attrs 爬取汽车之家 爬取汽车之家的资讯信息,它没有 ...
- ubuntu 打开 gbk编码的txt乱码
iconv -f gbk -t utf8 filename.txt > filename.txt.utf8
- spring常见注解说明
1. @ActiveProfiles("test") 我理解这个注解的主要用途是区分不同的环境.一般公司开发一个项目时,会区分测试环境.生产环境等.添加该注解,说明读取的profi ...
- Python并行编程(十):多线程性能评估
1.基本概念 GIL是CPython解释器引入的锁,GIL在解释器层面阻止了真正的并行运行.解释器在执行任何线程之前,必须等待当前正在运行的线程释放GIL,事实上,解释器会强迫想要运行的线程必须拿到G ...
- 禁止Centos系统You have new mail in /var/spool/mail/root提示
禁止Centos系统You have new mail in /var/spool/mail/root提示 https://blog.csdn.net/oyym_mv/article/details/ ...
- Upsource——对已签入的代码进行分享、讨论和审查代码
Upsource 一.Upsource简介 Upsource ,这是一个专门为软件开发团队所设计的源代码协作工具.Upsource能够与多种版本控制工具进行集成,包括Git.Mercurial.Sub ...
- intellij idea 重命名或复制一个项目(不用重启)
Idea 内无法直接修改Explorer 里文件夹的名称,只能手动改文件夹的名称. 目前找到的最好的方法: 1)重命名一个项目 在Idea 项目关闭状态下,在 Explorer (Windows) / ...
- SDUT3143:Combinatorial mathematics(组合数学)
题意:传送门 题目描述 As you know, shadow95 is pretty good at maths, especially combinatorial mathematics. Now ...
- DB_FILE_MULTIBLOCK_READ_COUNT对物理读和IO次数的影响
当执行SELECT语句时,如果在内存里找不到相应的数据,就会从磁盘读取进而缓存至LRU末端(冷端),这个过程就叫物理读.当相应数据已在内存,就会逻辑读. 物理读是磁盘读,逻辑读是内存读:内存读的速度远 ...