先来推荐一个检测内存泄漏的软件:JProfiler。很不错。本篇博文用到了这个软件。
接上一篇博文中那个经典面试问题。这里我用JProfiler对String对象的产生进行了监控。结果表明上篇博文的分析是正确的。
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2406
- * */
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- String str1 = "abc";
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2407
- * */
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- String str2 = new String("abc");
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2408
- * */
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- String str1 = "abc";
- String str2 = new String("abc");
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2408
- * */
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- String str1 = new String("abc");
- String str2 = new String("abc");
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2409
- * */
- public static void main(String[] args) {
- System.out.println("=====Start========");
- try {
- String str1 = "abc";
- String str2 = new String("def");
- Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("=====End========");
- }
- /*
- * 测试结果:String对象数目为:2409
- * */
好了,测试代码就这么多,分析结果很容易得出上篇博文的结论的。
此外:通过String str = new String("abc");创建出的pool中的String对象实际是没有引用的,这种对象很容易造成内存泄漏,java中的gc会自动在String pool中去清理这些没有引用的String对象。所以我们尽量不要使用new String("abc")的方式去创建String对象,事实上,effective java中也鄙视了这种创建方法。