简体   繁体   中英

Continuous Memory Allocation Not Causing Leakage

I'm trying to simulate an OutOfMemory exception in Android. My method is basically having a static ArrayList keep adding long[2048] arrays.

I had the program running for a while and it collected 685 instances of long[2048] . Using Android Studio's 3.0 profiler, the heap dump looks as such:

| 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.

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?

Also, what is the difference between shallow size , and retained size ?

PS: Here is the code:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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