There can be short and long answer.
The short answer is that you can theoretically count number of bytes occupied by each object stored in cache and calculate sum of them to know when it is the time to evict objects.
The longer answer is that it is not so simple. Indeed imagine that you have class like this:
class Simple {
private int n;
private byte b;
}
How much memory is needed to store instance of this class?
Let's say it is 4 bytes for int
and yet another byte for byte
, so 5 bytes. We do not count the memory needed to store reference to object itself.
This case is simple. But what about the following:
class Simple2 {
private int n;
private byte b;
private String s;
}
How much memory do you need now? 4+5+s.length*2
? Probably this is correct. But String is class and therefore s
is a reference. This reference may be reused in other object including object that is stored in the same cache. Do you want to count it twice or not? I do not know.
Let's say for simplicity that you want to count whole memory occupied by object. It means that you should go through the object recursively and calculate the memory occupied by its members. It is complicated and very performance expensive process.
Fortunately you can use other technique. Java instrumentation API allows to estimate number of bytes occupied by object. Moreover there is a project http://sizeof.sourceforge.net/ that implements this functionality and provides simple API for you.
Other possibility is to serialize object if it implements Serializable
and then check the size if serilized object. It is even more expensive and requires that your class must implement Serializable
. From other hand it does not need any 3rd party dependency.