Friday, December 7, 2012

Could we have memory leaks in Java?

Yes, here it is explained why.

Unused references

Code that keep useless references to objects that will never use again, and at the same time never drop those references; one may say those cases are not "true" memory leaks because there are still references to those objects around, but if the program never use those references again and also never drop them, it is completely equivalent to (and as bad as) a "true memory leak".

Java Native Interface

While implementing JNI functionality, you could
allocate memory via the other platform that you are using. Here is an example using C++. If you allocate memory via malloc, you have to free it manually. If you forget to do this, you get memory leak.

Resource leaks

They are just resource leaks, but it some case we could get memory leaks also. If you forget to release resource objects via the way they are proposed to release, you will get resource leaks. What could happened if you do not release resources? There could be some internal references to these resource objects, resulting in memory leaks.

JNI memory leaks

For JNI memory leaks, you could get help by dbx utility. Here is article how:

Tasks and Examples

Problem 1: Is there a memory leak here?
class Stack {
    private Object[] elements;
    private int size = 0;
   
    public Stack(int initialCapacity) {
        this.elements = new Object[initialCapacity];
    }

    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    public Object pop() {
        if (size > 0)
            return elements[--size];
       
        return null;
    }

    /**
    * 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)
        {
            Object[] oldElements = elements;
            elements = new Object[2 * elements.length + 1];
            System.arraycopy(oldElements, 0, elements, 0, size);
        }
    }
}



No comments:

Post a Comment