简体   繁体   English

连续内存分配不会导致泄漏

[英]Continuous Memory Allocation Not Causing Leakage

I'm trying to simulate an OutOfMemory exception in Android. 我正在尝试在Android中模拟OutOfMemory异常。 My method is basically having a static ArrayList keep adding long[2048] arrays. 我的方法基本上是让静态ArrayList继续添加long[2048]数组。

I had the program running for a while and it collected 685 instances of long[2048] . 我让程序运行了一段时间,它收集了685个long[2048]实例。 Using Android Studio's 3.0 profiler, the heap dump looks as such: 使用Android Studio的3.0分析器,堆转储如下所示:

| class name | alloc count | shallow size | retained size |
| ---------- | ----------- | ------------ | ------------- |
| long[]     | 685         | 9997168      | 9997168       |

So, the memory is NOT getting garbage collected. 因此,内存不会被垃圾回收。 Regardless, the app's heap memory remains at 40Mb and doesn't drop down. 无论如何,该应用程序的堆内存保持在40Mb,并且不会下降。

Why is this happening? 为什么会这样呢? Shouldn't the app be leaking memory like there is no tomorrow now?? 该应用程序不应该像现在没有明天那样泄漏内存吗? What trick does the JVM do this time? JVM这次有什么技巧?

Also, what is the difference between shallow size , and retained size ? 另外, shallow sizeretained size之间有什么区别?

PS: Here is the code: PS:这是代码:

    public class MainActivity extends AppCompatActivity {
    static List<long[]> myList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myList.add(loadStuff());
            }
        });
    }


    static long[] loadStuff() {
        return new long[2048];
    }
}

shallow size is the memory that is occupied right now whereas the retained size is the size that will be freed after collecting garbage see reference in here 浅的大小是当前占用的内存,而保留的大小是收集垃圾后将释放的大小,请参见此处的参考。

shallow vs retained size 浅色与保留尺寸

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM