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

猜你喜欢

转载自www.cnblogs.com/yszzu/p/9270682.html