Reputation: 19582
I am reading about Weak References.
I am using the code to study from here. It is very simple.
private void doFunction() throws InterruptedException {
Map<Integer, String> map = new HashMap<Integer, String>();
myMap = new WeakReference<Map<Integer, String>>(map);
map = null;
int i = 0;
while (true) {
if (myMap != null && myMap.get() != null) {
myMap.get().put(i++, "test" + i);
System.out.println("im still working!!!!");
}
else {
System.out.println("*******im free at:"+i+"*******");
Thread.sleep(5000);
if(myMap != null){
System.out.println("*******myMap is not null*******");
}
}
}
I did not request a small heap size or any size via –Xms and –Xmx
but was able to see the values removed from the cache when i == 15312
.
So after 15312
objects in the Map
the GC starts to remove entries.
My question: Isn't 15312
too low for a 32 bit machine
with 4 GB
of memory? I was expecting a much higher value before the references are starting to be removed.
Am I wrong on this? How can one evaluate at which points the objects will start to be removed?
Upvotes: 0
Views: 230
Reputation: 12819
The point of the WeakReference
is that you do not care when the VM will garbage collect the stuff. The VM will then do what it it considers is The Right Thing To Do in terms of the memory footprint & performance mix.
The fact the GC is starting to collect your objects after 15312 objects could merely be a coincidence, it'll also be dependent on how the GC is implemented and/or configured (a different version of the JVM might collect differently). Again, if you're using WeakReferences
, you should expect your stuff will be collected at a random point in time, and efforts to try and control when this happens are futile.
So no, 15312 isn't "low for a 32 bit machine with 4GB of memory, since the VM could collect much earlier than "when the memory is full", or it could collect "never until the memory is full" - this is implementation & configuration dependent, and unless you're doing very specifically targeted performance optimization, in a very specific usage scenario, for a specific VM version on a specific architecture, time spent trying to change this is probably wasted.
Upvotes: 2