I have encountered a somewhat baffling problem with the simple task of filling an Array dynamically in Java. The following is a snapshot from where the problem originates:
entries = new Object[ (n = _entries.length + 1) ] ;
for(i = 0 ; i < n ; i++) {
entry = ( i == (n - 1) ) ? addition : _entries[i] ;
entries[i] = entry ;
//...
}
Where _entries is a source Array (field of the class); entries is initialized as an Array of Objects
Object[] entries = null ;
and addition is the Object to be added (passed as an Argument to the method this code is in).
The code passes the compiler but results in a memory-leak when called. I was able to narrow down the cause to the line where the code attempts to fill the new Array
entries[i] = entry ;
however, I cannot think of any reason why this would cause a memory-leak. I’m guessing the root of the issue must be either an extremely stupid fault on my part or an extremely arcane problem with Java. 🙂
If you need more background let me know.
Edit:
Tomcat’s log tells me:
A web application appears to have started a thread named … but has failed to stop it.
This is very likely to create a memory leak.
Other than that obviously the page loading the class does not finish loading or loads very slowly.
Edit:
The problem might be somewhere else (at a more expected location) after all. Apparently Tomcat wasn’t loading the class files all the time when I tried to pin down the faulty code and this mislead me a bit. I now suspect a infinte for-each loop caused by a defective Iterator implementation up in the call stack to be at fault.
In any case, thanks for your input! Always much appreciated!
I will use a Collection (probably a Vector) instead of an Array as a work-around; still, I’d like to know what the problem here is.
TIA,
FK82
I cannot see a memory leak, but your code is more complicated than it needs to be. How about this:
No need to check if you are at the last entry all the time and you could use a array copy method as suggested by Alison.
Think of this post as a comment. I just posted it as an answer because I don’t know how code is formatted in comments…