黑马程序员技术交流社区

标题: 面试重点之内存泄露 [打印本页]

作者: 杨栋    时间: 2013-8-22 14:49
标题: 面试重点之内存泄露
内存泄漏也称作“存储渗漏”,用动态存储分配函数动态开辟的空间,在使用完毕后未释放,结果导致一直占据该内存单元。直到程序结束。即所谓内存泄漏。简单地说就是申请了一块内存空间,使用完毕后没有释放掉。它的一般表现方式是程序运行时间越长,占用内存越多,最终用尽全部内存,整个系统崩溃。由程序申请的一块内存,且没有任何一个指针指向它,那么这块内存就泄露了

package com.baidu.first;

public class ReflectPoint {
    public String str1;
    public int i;
    public String str2="asdfghaaa";
    public ReflectPoint(String str1, int i) {
        super();
        this.str1 = str1;
        this.i = i;
    }
    public String toString()
    {
        return str1+":"+str2;
    }
   
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + i;
        result = prime * result + ((str1 == null) ? 0 : str1.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ReflectPoint other = (ReflectPoint) obj;
        if (i != other.i)
            return false;
        if (str1 == null) {
            if (other.str1 != null)
                return false;
        } else if (!str1.equals(other.str1))
            return false;
        return true;
    }

}

package com.baidu.first;
import java.util.*;

public class ReflectText1 {
    public static void main(String[] args){
        Collection collection=new HashSet();
        ReflectPoint rft1=new ReflectPoint("asd",3);
        ReflectPoint rft2=new ReflectPoint("asdf",4);
        ReflectPoint rft3=new ReflectPoint("asds",3);
        collection.add(rft1);
        collection.add(rft2);
        collection.add(rft3);
        collection.add(rft1);
        rft1.i=8;//哈希集合中的元素被修给后该对象就移除不掉了,这就叫内存泄露也叫做内存渗漏
        collection.remove(rft1);
        System.out.println(collection.size());
    }

}
在这个例子中造成内存渗漏的原因是修改了决定哈希值的字段,导致这个元素不在哈希集合原来的区域(rft1这个引用所指向的位置),这个元素跑到了一个新的没有被引用所指向的区域,所以删除不掉了

作者: Boeing_Bick    时间: 2013-8-22 16:31
不是很懂。。收藏了
作者: penpen    时间: 2013-8-23 00:23
原来这就是内存泄露啊,学习了,谢谢楼主。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2