Download presentation
Presentation is loading. Please wait.
Published byPrudence Gardner Modified over 6 years ago
1
Memory leaks in Java? Not exactly memory leak
but reduced performance due to increased garbage collection activities and increased memory footprint Good Java Programming 8/23/2018
2
Stack implementation in Java
public class MyStack { private Object[] stackElements; private int currentSize = 0; private static int INIT_CAPACITY = 100; public MyStack() { stackElements = new Object[INIT_CAPACITY]; } public void push(Object objAdd) { ensureCapacity(); currentSize++; stackElements[currentSize] = objAdd; // code continued in next slide Good Java Programming 8/23/2018
3
Stack implementation in Java (contd)
public Object pop() { if (0 == currentSize) throw new EmptyStackException(); currentSize--; return stackElements[currentSize]; } private void ensureCapacity() { if (stackElements.length == currentSize) { // double the array + 1 // copyOf method: stackElements = Arrays.copyOf(stackElements, 2 * currentSize + 1); } // end class MyStack Good Java Programming 8/23/2018
4
Memory leaks in Java? As the stack grows and shrinks objects that were popped off will not be garbage collected even if the driver/client code, which is using the Stack, does not have those references Why? Stack maintains obsolete references to these objects Obsolete reference: a reference that will never be dereferenced again This is called Unintentional Object Retention Note that such objects may contain other references and so on Good Java Programming 8/23/2018
5
Unintentional Object Retention
Note that such objects may contain other references and so on Guideline Always null the references Added benefit accidental use of that reference (array index in this case) will result in a NullPointerException Do NOT null every reference overkill, cluttered code Define each variable in the narrowest possible scope and let it fall out of scope (we will discuss this later) Good Java Programming 8/23/2018
6
Eliminate obsolete references
public Object pop() { if (0 == currentSize) throw new EmptyStackException(); Object resultObj = stackElements[currentSize]; // elimnate the obsolete reference by setting it to null stackElements[currentSize] = null; currentSize--; return resultObj; } Good Java Programming 8/23/2018
7
Design Guideline Eliminate obsolete object references
Good Java Programming 8/23/2018
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.