M
mitch gart
In our program we create a huge number of objects of a class,
call it Apple. Apples are immutable. Many of them have the same
values: in more than 90% of the cases when we are constructing a new
apple2, apple2.equals(apple1) for some other object apple1 which was
already created.
Our program is running into memory problems and I'd like to replace
the constructor for Apple with a factory method which checks to see
if there is already an existing object, and if so returns a reference
to that, otherwise constructs a new one if really needed.
This seems like a good use of WeakHashMap because we would like to
maintain a list of existing objects, but allow them to be garbage
collected when the last reference goes away. However in thinking about
the details I have a question.
Suppose when we put an object into the WeakHashMap we do
map.put(apple2, apple2);
and when we look for one we do
if (map.containsKey(apple2)) {
return map.get(apple2);
} else {
return new Apple(...)
}
It seems like that would work, except that the values in a
WeakHashMap (as opposed to the keys) are kept as strong references,
not weak references. It seems like doing this would make it so
no apples were ever garbage collected.
Any ideas how to do this? Thanks,
- Mitch
call it Apple. Apples are immutable. Many of them have the same
values: in more than 90% of the cases when we are constructing a new
apple2, apple2.equals(apple1) for some other object apple1 which was
already created.
Our program is running into memory problems and I'd like to replace
the constructor for Apple with a factory method which checks to see
if there is already an existing object, and if so returns a reference
to that, otherwise constructs a new one if really needed.
This seems like a good use of WeakHashMap because we would like to
maintain a list of existing objects, but allow them to be garbage
collected when the last reference goes away. However in thinking about
the details I have a question.
Suppose when we put an object into the WeakHashMap we do
map.put(apple2, apple2);
and when we look for one we do
if (map.containsKey(apple2)) {
return map.get(apple2);
} else {
return new Apple(...)
}
It seems like that would work, except that the values in a
WeakHashMap (as opposed to the keys) are kept as strong references,
not weak references. It seems like doing this would make it so
no apples were ever garbage collected.
Any ideas how to do this? Thanks,
- Mitch