[英]Why does creating ImageViews with a loop from an ArrayList cause a memory error?
[英]Does While true loop always cause Out of memory error?
我一直認為一段時間(真){...Any code..} 總是會導致 out of memory 錯誤。
但是當我 go 在 java 更深時,它似乎可能不是那樣的。
我無法確認,但如果我們有一段時間只進行計算,我們預計不會出現 memory 錯誤,只會對 CPU 性能造成非常不利的影響,對吧? 另一方面,如果我們總是需要更多的 memory,則預計會出現 memory 錯誤。
我下面有3個案例。
我沒有測試我的電腦,因為我只有一台,希望有人知道。
代碼
import java.util.*;
public class HelloLeak{
//calculations only, MemoryLeak?
public static void outofmemo1(){
long i = 0;
while (true)
{
i = i * i;
}
}
//adding infinite number of objects, memory leak confirmed.
public static void outofmemo2(){
int i = 0;
List<Integer> l = new ArrayList<>();
while (true)
{
l.add(i);
}
}
//Creating infinite number of ArrayList objects, will garbage collector clear the unused objects or we will get memory leak?
public static void outofmemo3(){
List<Integer> l = new ArrayList<>();
while (true)
{
l = new ArrayList<>();
}
}
public static void main(String []args){
outofmemo1();
//outofmemo2();
//outofmemo3();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.