Dav*_* J. 5 java clojure guava
我想知道缓存中正在使用多少字节.这在确定合理的尺寸方面很有用.有什么好方法可以计算Google Guava缓存中使用的字节数?
该stats方法没有给出我想要的东西; 它不包括缓存中字节数的度量标准.
这种asMap方法是我迄今为止发现的最佳方法.获得此信息后,可以使用In Java中显示的一些技术,确定对象大小的最佳方法是什么?.但是,坦率地说,这些看起来相当痛苦,至少从Clojure代码库来看.为了避免一些依赖,我目前正在使用Nippy,一个Clojure序列化库的粗略快捷方式:(count (nippy/freeze (.asMap cache))).我正在寻找更好的方法.
我正在使用Clojure代码库中的Google Guava缓存,但我的问题不一定是Clojure特有的; 在大多数情况下,Java互操作相对容易.
更新:回应下面的评论的一些背景.首先,我想知道我是否忽略了Google Guava缓存API的有用部分.其次,我不知道我链接的通用方法(用于计算堆上的内存使用情况)是否适用于Guava.更广泛地说,查找缓存大小利用率是一个重要的用例,所以我有点惊讶它没有更好的在线记录.
Java (and by extension Guava) does not provide any easy or meaningful way to measure "bytes used" by an object or data structure. Notably there isn't even a single coherent definition of that concept, since an object can be referenced from multiple other objects and there's no notion of bytes being "owned" by a particular data structure. Other languages like Rust have this notion of ownership, but Java does not.
For example, how many bytes does an instance of MyClass use?
public class MyClass {
private static final int[] BIG_ARRAY = new int[1_000_000];
private final int[] myArray = BIG_ARRAY;
}
Run Code Online (Sandbox Code Playgroud)
Clearly the class uses a lot of memory, but each instance only uses up a few bytes in order to reference the statically allocated array. You can create thousands of MyClass instances and see very little memory impact, and even if all instances are GCed BIG_ARRAY will stick around. So it seems wrong to say that an instance of MyClass "uses" the backing array's bytes.
You can determine how many bytes the cache itself uses (e.g. to compare it to using a ConcurrentHashMap or another collection) based on the fields and instances a Cache maintains. Guava links to this helpful resource of data structure memory footprints you can reference, but obviously this won't include the contents of the cache, just its structure.
Needless to say, as Louis Wasserman commented, you should look for a different metric that more directly tells you what you need to know. For instance you might be more interested in the hit rate, which tells you how efficiently you're using whatever data your cache is retaining.
| 归档时间: |
|
| 查看次数: |
901 次 |
| 最近记录: |