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才怪呢!
HashCode重载不当造成内存泄漏
最新推荐文章于 2024-04-26 09:00:00 发布
博客主要讲述Java中hashCode方法重载不当易造成内存泄漏,以Set为例,修改对象属性后contains方法可能返回错误结果。若Set为静态成员,会一直持有对象。在服务器端运行此类代码后果严重,如Hibernate中操作PO修改影响hashcode字段,易致OutOfMemory。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Python3.10
Conda
Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本
14

被折叠的 条评论
为什么被折叠?



