jcmd jmap应用:一个String经典笔试题的验证

笔试题:

String strA = new String("123123");这一行中创建了几个String对象??
1 public class StringHeapCountTest {
2 
3     public static void main(String[] args) {
4         String strA = new String("123123");
5         System.out.println(1);
6     }
7 
8 }
这个题主要考察应试者对java内存结构(堆、非堆、栈、本地方法栈)、堆中的常量值、类加载和对象创建过程的了解程度。

一. 基准数据:首先我们看一下下面的代码, 什么都没有时在jvm堆中创建了多少String

1 public class StringHeapCountTest {
2 
3     public static void main(String[] args) {
4         System.out.println(1);
5     }
6 
7 }

在第4行打断点,然后使用jps打印出当前进程,再使用jmap -histo xxx打印当前jvm中的对象数。如下图所示,String有3778个

二,. 再看如下代码中String的个数

1 public class StringHeapCountTest {
2 
3     public static void main(String[] args) {
4         String strA = "123123";
5         System.out.println(1);
6     }
7 
8 }

如下图所示,String有3779个 ,比上一个实验多创建一个

三、 最后我们恢复文章开头题目中的第4行,再统计一下jvm中String的个数.如下图所示,3780个,创建两个

这个题目有很多变种,这里给出验证方法供参考。

jmap命令手册

-histo[:live]  to print histogram of java object heap; if the "live" suboption is specified, only count live objects

 @See String.intern()

GC ROOT: http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.mat.ui.help%2Fconcepts%2Fgcroots.html&cp=37_2_3

jcmd 1.7新增命令 https://www.jianshu.com/p/388e35d8a09b,  可以替代jps jstack jmap jinfo

jcmd pid GC.class_histogram | grep java.lang.String

jcmd 9952 help 
The following commands are available:
...
VM.native_memory
 ... 
Thread.print                 打印线程栈
GC.class_stats            对象个数,占用字节数...
GC.class_histogram    打印class统计信息:对象个数,占用字节数。 只有两列,内容比GC.class_stats精简
GC.heap_dump            堆dump
GC.run_finalization
GC.run                         手动触发GC
VM.uptime                    启动时间
VM.flags                       启动参数 -XX
VM.system_properties 系统参数
VM.command_line       启动命令
VM.version 

原文地址:https://www.cnblogs.com/yszzu/p/9270682.html