Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing cached instances

Tags:

java

caching

I have an application that uses a data structure Point. Let's say that overall there are 50 distinct instances of Point (meaning p1.equals(p2) == false). However during calculation loads of new instances are created, that are actually the same as already instantiated objects.

As these instances are stored this has a heavy impact on memory consumption: 50 distinct Points are represented by 500'000 instances of Point. In the data structure there is nothing that would prevent the reuse of already present instances. For that reason I created a cache:

HashMap<Point, Point> pointCache = new HashMap<>();

So I can check if the point is present and add it if it is not. This kind of cache however seems like a bit of overkill, as the key and the value are essentially the same.

Furthermore I already have a map present:

HashMap<Point, Boolean> flag = new HashMap<>();

What I am curious about is: Is there a map like data structure that I could use for flag that would allow the retrieval of the key? If not is there any other data structure that I could use for the cache that would be more like a set and would allow easy checking and retrieval?

EDIT: For completeness, the Point class I am using is javafx.geometry.Point2D and therefore nothing that I can change.

like image 997
hotzst Avatar asked Aug 29 '26 12:08

hotzst


1 Answers

Let's assume, for the sake of this answer, that the uniqueness of a Point is determined by two int coordinates, x and y (you can change that easily to fit the actual parameters that determine your Point's uniqueness).

You don't want to create a Point instance in order to determine if that Point already exists in some HashSet or HashMap. That defeats the purpose of avoiding creation of multiple instances (though using a HashMap or HashSet would prevent you from keeping all those duplicate instances, and the GC will release them soon, so it may be enough to solve the memory consumption issue).

I'm suggesting that you have a static Point getPoint(int x,int y) method in your Point class. That method would check inside a static internal HashMap<Integer,HashMap<Integer,Point>> whether those x,y coordinates already have a corresponding Point instance and return that instance. If an instance doesn't exist, it will be created and added to the HashMap.

This is similar to what Integer.valueOf(int) does for small integers - it returns a cached Integer instance instead of creating a new one.

like image 148
Eran Avatar answered Aug 31 '26 03:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!