HashCode重载不当造成内存泄漏

来源:互联网 发布:淘宝女士皮鞋 编辑:程序博客网 时间:2024/05/18 01:40
import java.util.HashSet;import java.util.Set;/** *如果hashCode的方法重载不当,很容易造成内存泄漏,特别是当Set为静态的时候 *并且,中间容易出现奇怪的现象,明明已经添加到Set当中,但是contains方法却返回false  */public class HashTest {    public static void main(String[] args){        Set hashSet = new HashSet();        Student student = new Student();        student.setName("a");        student.setNo("M");        hashSet.add(student);        student.setName("aaaaa");        boolean isOk = hashSet.contains(student);                       System.out.println(isOk);               hashSet.add(student);        int size =hashSet.size();        System.out.println(size);        hashSet.remove(student);        size =hashSet.size();        System.out.println(size);            }    }class Student {            public Student(){        }        private String name;        private String no;        public String getName() {            return name;        }        public String getNo() {            return no;        }        public void setName(String string) {            name = string;        }        public void setNo(String string) {            no = string;        }                public int hashCode() {            return no.hashCode()+name.hashCode();        }    }
执行一下上面的程序,其结果可能有点出乎你的意料。

如果Set声明为一个类的static成员,那么hashSet就会始终持“被遗忘”的对象,直到程序退出。

如过类似的代码运行在服务器端,其结果就可想而知了。
不要以为这种情况不常见,这是Java中最导致内存泄漏的最好办法。
比如Hibernate中生成的那些PO,如果在操作的过程中修改了影响生成hashcode的字段,
而Hibernate运用了缓存机制,相信,运行一段时间之后,你的程序不出现OutOfMemory才怪呢!
原创粉丝点击