简体   繁体   中英

is these code cause memory leak in java?

    ArrayList<Object> list = new ArrayList<Object>();
    for (int i = 0; i < 10; i++) {
        Object o = new Object();
        list.add(o);
    }
    list = null;

or

    ArrayList<Object> list = new ArrayList<Object>();
    for (int i = 0; i < 10; i++) {
        Object o = new Object();
        list.add(o);
        o = null;
    }

which code block will cause memory leak in java, why?

If neither will cause memory leak, how can I cause a memory leak~ (I want some code)

I do not think that any memory leak is happening in the code given above. Even though you are setting s to null "string" object is still referred by the ArrayList items. So those string objects still have active references after the loop ends.

Memory leaks are still possible in Java through static object reference. Please refer the link .

两种情况都不会导致内存泄漏,并且所有对象都将在代码块末尾自动释放。

Neither example has a memory leak. In Java it's not worth explicitly setting a variable to null just to help the garbage collector out a bit.

Note that there are situations where long-lived references to large objects (say in a cache) do need to be set to null to avoid unconstrained memory growth (leaks).

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