简体   繁体   中英

Java ArrayList Memory Issue

I have the following code:

  result = binding.downloadData(sourceURLString.replace("{CAT_ID}", catId), Data.class);

  ArrayList<Data> mAllProducts = result.getProducts();
  cloneList(mAllProducts);
  System.gc();

And here is the deep copy of the mAllProducts ArrayList

  static List<Data> clone;
  public static void cloneList(ArrayList<Data> list) {
    clone = new ArrayList<Data>();
    for(Data item: list){ 
        clone.add(new Data(item));
         }
 }

Data Constructor:

 public Data(Data item2) {
    this.imageUrl = item2.imageUrl;
                   *
                   *
  }

My questions are:

  1. Will the mAllProducts arraylist collected by the garbage collector?
  2. Is the clone list a passed by value ArrayList?
  3. If the answer at the 2nd question is yes, that means that the clone arraylist doesn't have a reference to the memory?
  4. And finally, if the answer at the second question is yes, that means that will stay at the memory only for the time is being used by the system and then will be garbage collected?

1) No way to know, your gc call is merely a suggestion that the JVM try to perform a collection.

2) Everything in Java is pass by value.

3) I don't know what you mean. But your clone, assuming it creates new items for the list, and the items don't share references to any objects, is completely separate from the original list. Primitive values like ints are immutable, it's only object instances you have to worry about. It seems you are using a copy constructor, so be extra careful you copy any objects each item contains, as well as any items those children might contain; your copy needs to be deep.

4) I don't know what you mean. If you don't have any references to the original it will be eligible for collection the next time the GC runs.

Will the mAllProducts arraylist collected by the garbage collector?

Only when 1) The garbage collector decides to do so and 2) When it falls out of scope

Is the clone list a passed by value ArrayList?

Yes

If the answer at the 2nd question is yes, that means that the clone arraylist doesn't have a reference to the memory?

Definitely needs a reference to some point in memory, else it can't exist in a logical system ie a computer.

And finally, if the answer at the second question is yes, that means that will stay at the memory only for the time is being used by the system and then will be garbage collected?

Again the garbage collector will collect it when it is deemed fit to do so.

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