Thanks for the reply, i have vector declared globally and In a method, in each iteration, i remove and add new elements in the vector. so i use remove(index)
in each iteration. I am suspecting whether the memory will get freed when i call
remove() method and use that memory for adding new element in each iteration.
Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak. This is particularly true if the class has been declared static and exists for the life of the application. When you remove an element, the object sorted in that element is dereferenced and the re-sizing of that collection is taken care of by the JVM. But the collection object in itself will be marked as trash and the memory allocated will be dereferenced only when it passes out of scope.
there are two pieces of memory in question. The object in the collection, and the collection itself.
when you call remove on an object (or clear), if nothing else is referencing that object, it can be freed (gc-ed). The collection however, most probably still holds onto the memory used to hold the object reference. Some collections have methods to compact the collection to it's minimal size.
Hi,
Vectors hold only references to other objects. Hence, when you "add or remove" elements to vectors, you are only adding or removing references to other objects in the heap.
Memory taken by objects in the heap is freed as per the whims of the garbage collector. Unless your program does some memory-intensive computation, the garbage collector might not even run during your program's execution phase.
If you have declared Vector v = new Vector();
, the JRE will create a vector object in the heap, capable of storing 10 references. If you try to add an 11th reference to the vector, the Vector object will grow automatically by a default increment. Since in your code you are adding and removing references continuously, the Vector size will remain the same as long as the number of references never exceeds 10.
Regards,
Kumar.
Thanks for all your replies.. I am iterating in for loop continously sleeping for 1minute ..This has been running for last 1 day.... In each iteration the add and remove into the vector and hashtable happens....As i said vector and hashtable are declared globally in the program.If this is the scenario..what way i can optimize my code to not to have memory leak.