string机制2

先来推荐一个检测内存泄漏的软件:JProfiler。很不错。本篇博文用到了这个软件。

接上一篇博文中那个经典面试问题。这里我用JProfiler对String对象的产生进行了监控。结果表明上篇博文的分析是正确的。

  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  5.     } catch (InterruptedException e) {
  6.         e.printStackTrace();
  7.     }
  8.     System.out.println("=====End========");
  9. }
  10. /*
  11.  * 测试结果:String对象数目为:2406
  12.  * */
  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         String str1 = "abc";
  5.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  6.     } catch (InterruptedException e) {
  7.         e.printStackTrace();
  8.     }
  9.     System.out.println("=====End========");
  10. }
  11. /*
  12.  * 测试结果:String对象数目为:2407
  13.  * */
  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         String str2 = new String("abc");
  5.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  6.     } catch (InterruptedException e) {
  7.         e.printStackTrace();
  8.     }
  9.     System.out.println("=====End========");
  10. }
  11. /*
  12.  * 测试结果:String对象数目为:2408
  13.  * */
  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         String str1 = "abc";
  5.         String str2 = new String("abc");
  6.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  7.     } catch (InterruptedException e) {
  8.         e.printStackTrace();
  9.     }
  10.     System.out.println("=====End========");
  11. }
  12. /*
  13.  * 测试结果:String对象数目为:2408
  14.  * */
  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         String str1 = new String("abc");
  5.         String str2 = new String("abc");
  6.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  7.     } catch (InterruptedException e) {
  8.         e.printStackTrace();
  9.     }
  10.     System.out.println("=====End========");
  11. }
  12. /*
  13.  * 测试结果:String对象数目为:2409
  14.  * */
  1. public static void main(String[] args) {
  2.     System.out.println("=====Start========");
  3.     try {
  4.         String str1 = "abc";
  5.         String str2 = new String("def");
  6.         Thread.sleep(500L*1000L);//停留5分钟,目的是为了方便JProfiler来监控内存。
  7.     } catch (InterruptedException e) {
  8.         e.printStackTrace();
  9.     }
  10.     System.out.println("=====End========");
  11. }
  12. /*
  13.  * 测试结果:String对象数目为:2409
  14.  * */

好了,测试代码就这么多,分析结果很容易得出上篇博文的结论的。

此外:通过String str = new String("abc");创建出的pool中的String对象实际是没有引用的,这种对象很容易造成内存泄漏,java中的gc会自动在String pool中去清理这些没有引用的String对象。所以我们尽量不要使用new String("abc")的方式去创建String对象,事实上,effective java中也鄙视了这种创建方法。

你可能感兴趣的:(java,String,面试,测试)