Alex Rivera | Logout

Caching strategy for small immutable objects in Java?

Asked 2011-04-25T22:11:04.090
9

I am developing an app that creates a large number of small, immutable Java objects. An example might be:

public class Point {
  final int x;
  final int y;
  final int z;
  .....
}

Where it is likely that many instances of Point will need to refer to the same (x,y,z) location.

To what extent does it make sense to try to cache and re-use such objects during the lifetime of the application? Any special tricks to handle this kind of situation?

Edit
Report

2 Answers

3

How many instances will share the same coordinates, how many will exist at the same time, and how many will be discarded?

Reusing the objects only has benefits if a significant percentage of live objects at one time are duplicates (at least 20%, I'd say) and overall memory usage is problematic. And if objects are discarded frequently, you have to construct the cache in a way that prevents it from becoming a memory leak (probably using soft/weak references).

answered 2011-04-25T22:19:49.333
1

Remember that caching these objects will influence concurrency and garbage collection in (most likely) a bad way. I wouldn't do it unless the other objects that refer to the points are long lived too.

answered 2011-04-25T22:26:42.010

Your Answer