Memory leaks and memory overflows

https://www.cnblogs.com/panxuejun/p/5883044.htmlThis
blog is well written

A few sentences are summarized as follows:
1. Memory leak: Objects that are no longer in use continue to have comrade-in-arms memory or useless memory is not released, resulting in a waste of memory space.
Cause: Long-lived objects hold references to short-lived objects.
Here are two examples:
1. Memory leaks caused by static collection
classes . The use of HashMap, Vector, etc. is the most prone to memory leaks. The life cycle of these static variables is consistent with the application, and all the objects they refer to cannot be released. Because they will always be referenced by Vector et al.

Static Vector v = new Vector(10);
for (int i = 1; i<100; i++)
{
Object o = new Object();
v.add(o);
o = null;
}//

In this example, apply for the Object object cyclically, and put the applied object into a Vector. If only the reference itself is released (o=null), the Vector still refers to the object, so this object is not recyclable for GC of. Therefore, if an object must be removed from the Vector after it is added to the Vector, the easiest way is to set the Vector object to null.

2. When the object properties in the collection are modified, calling the remove() method does not work.

public static void main(String[] args)
{
Set<Person> set = new HashSet<Person>();
Person p1 = new Person("唐僧","pwd1",25);
Person p2 = new Person("孙悟空","pwd2",26);
Person p3 = new Person("猪八戒","pwd3",27);
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println("总共有:"+set.size()+" 个元素!"); //结果:总共有:3 个元素!
p3.setAge(2); //修改p3的年龄,此时p3元素对应的hashcode值发生改变

set.remove(p3); //此时remove不掉,造成内存泄漏

set.add(p3); //重新添加,居然添加成功
System.out.println("总共有:"+set.size()+" 个元素!"); //结果:总共有:4 个元素!
for (Person person : set)
{
System.out.println(person);
}
}

Second, memory overflow
Memory leak may have no effect, if the program continues to run, memory leak may lead to memory overflow.
Several situations of memory overflow:
1. OutOfMemory exception. In addition to the program counter, OutOfMemory exceptions may occur in several other running areas of virtual machine memory.
2. Stack Overflow StackOverFlowError The stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine, and an exception will be thrown.

The reasons are summarized as follows:
1. The amount of data loaded in the memory is too large, such as taking too much data from the database at one time.
2. There are references to objects in the collection class, and they are not emptied after use. Yes, the JVM cannot be recycled
. 3. Code There is an infinite loop
4. The memory value of the startup parameter is set too small

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324477614&siteId=291194637