Loading

Java String内存释放

Java String内存释放

这是一个坑,Java对于String对象,不进行内存的回收;

处理大数据量的时候,少用String。

与JDK有关系;jdk1.6环境下,内存只占用10M,jdk1.8情况下,内存占用300M

package com.test;

public class TestMem {
    public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
            
            @Override
            public void run() {
                
                while(true){
                    try {
                        str();
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("before");
                    System.gc();
                    System.out.println("end");
                }
            }

            private void str() {
                String str = "";
                for(int i=1;i<10000;i++){
                    str += "asdfasdfasdfasdf";
                    System.out.println(i);
                }
                str = str + "";
                str = null;
                System.out.println("asdfsdfa");
            }
        });
        
        t.start();

    }
}

 

posted @ 2017-06-02 06:46  stono  阅读(2843)  评论(0编辑  收藏  举报