Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing deallocation of large cache object in Java

I use a large (millions) entries hashmap to cache values needed by an algorithm, the key is a combination of two objects as a long. Since it grows continuously (because keys in the map changes, so old ones are not needed anymore) it would be nice to be able to force wiping all the data contained in it and start again during the execution, is there a way to do effectively in Java?

I mean release the associated memory (about 1-1.5gb of hashmap) and restart from the empty hashmap..

like image 852
Jack Avatar asked Mar 09 '10 02:03

Jack


People also ask

Is it possible to force garbage collection in Java?

Unfortunately, this desire to immediately free up memory must go unrequited, as there is no way to force garbage collection (GC) in Java.

Is there any way to deallocate memory in Java?

In Java, the programmer allocates memory by creating a new object. There is no way to de-allocate that memory. Periodically the Garbage Collector sweeps through the memory allocated to the program, and determines which objects it can safely destroy, therefore releasing the memory.

How do you deallocate an object in Java?

When an object completes its life-cycle the garbage collector deletes that object and deallocates or releases the memory occupied by the object. It is also known as finalizers that are non-deterministic. In Java, the allocation and deallocation of objects handled by the garbage collector.

How do you clean up unused objects in Java?

In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++.


1 Answers

You can call HashMap.clear(). That will remove all data. Note that this will only discard all entries, but keep the internal array used to store the entries at the same size (rather than shrinking to an initial capacity). If you also need to eliminate that, the easiest way would be to discard the whole HashMap and replace it with a new instance. That of course only works if you control who has a pointer to the map.

As for reclaiming the memory, you will have to let the garbage collector do its work.

Are your values also Long? In this case, you may want to look at a more (memory-) efficient implementation than the generic HashMap, such as the TLongLongHashMap found in the GNU Trove library. That should save a lot of memory.

like image 191
Thilo Avatar answered Oct 30 '22 14:10

Thilo