问题
I am reading the book called "Effective Java" by Joshua Bloch and there is a piece of code which leads to memory leaks.
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly
* doubling the capacity each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
The pop method should be replaced with
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
It's clear to me. Can the code (see below) lead to memory leaks? E.g., I rotate the screen a lot of times and private ArrayList<String> mArrayList = new ArrayList<String>(CAPASITY); allocates memory each time.
public class MainActivity extends Activity implements OnClickListener {
private static final int CAPASITY = 10000;
private ArrayList<String> mArrayList = new ArrayList<String>(CAPASITY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Some work on mArrayList
}
@Override
public void onClick(View v) {
// Some work on mArrayList
}
@Override
protected void onDestroy() {
super.onDestroy();
// TODO: mArrayList = null to prevent memory leaks. Is it necessary to do it?
}
}
回答1:
// TODO: mArrayList = null to prevent memory leaks. Is it necessary to do it?
No, the activity object and its members such as mArrayList can be garbage collected. Your activity code does not show anything that would hold object references unnecessarily long.
来源:https://stackoverflow.com/questions/16912496/android-memory-leaks-understanding