简体   繁体   中英

Prevent Memory Leak in Array List in java

I have a scenario as below:

class Example {

  private List<Long> timeFrames;  //  Line 2

  private Example() {
    this.timeFrames = new ArrayList<>();
  }

  public static Example getExample() { return new Example();  }

  ...
  
  public Integer startTimeFrame() {
    Long startTimeStamp = new Date().getTime();
    this.timeFrames.add(startTimeStamp);
    return this.timeFrames.indexOf(startTimeStamp);
  }

  public Long stopTimeFrame(Integer timeFrameIdentifier){
    Long startTimeStamp = this.timeFrames.get(timeFrameIdentifier);
    return new Date().getTime() - startTimeStamp;
  }

}

Now, during the code review my architect has given the following comment at Line No. 2 - "This is potentially be the cause of memory leak because you never clear the elements"

How can we handle this?

EDIT:

I have updated the Java Code. Actually we have code in Node Js, which we are converting into Java.

In the Node Js code, we have the "stopTimeFrame()" method as below:

  public stopTimeFrame(timeFrameIdentifier: number): number {
    const startTimeStamp = this.timeFrames.splice(timeFrameIdentifier, 1)[0]

    return new Date().getTime() - startTimeStamp;
  }

So, In Node Js code, they are using 'Splice()' method. I don't have much knowledge on Node Js. So I just googled what is the usage of splice() in Node Js.

As per documentation (w.r.t the above code ), the splice() method adds new items at position 'timeFrameIdentifier' and remove 1 item.

So, I think my Reviewer meant this when he said I am not clearing the elements.

Can you please help me how can we convert the "stopTimeFrame()" method in Java so its functionality is same as in Node Js (where its using splice() to remove an item everytime)?

Just make sure that you remove unused frames from your list. The implementation does remove references to the removed Long objects so that if there are no other references to them, the garbage collector can take care of them if needed. Then there will be no memory leak.

For exmample here is the implementation of one of the remove methods:

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

You notice the line:

    elementData[--size] = null; // clear to let GC do its work

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