0
尝试缓存一些MB数量的对象时,我观察到Ehcache会在保持缓存大小的同时将其大小加倍。Ehcache为什么加倍存储在内存中的字符串的大小?
为什么会发生这种情况?这是一种优化吗?它可以被取消吗?
以下代码:
public class Main {
public static void main(String[] args) {
CacheManager manager = CacheManager.newInstance();
Cache oneCache = manager.getCache("OneCache");
String oneMbString = generateDummyString(1024 * 1024);
Element bigElement = new Element("key", oneMbString);
oneCache.put(bigElement);
System.out.println("size: "+ oneCache.getSize());
System.out.println("inMemorySize: " + oneCache.calculateInMemorySize());
System.out.println("size of string: " + oneMbString.getBytes().length);
}
/**
* Generate a dummy string
*
* @param size the size of the string in bytes.
* @return
*/
private static String generateDummyString(int size) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("a");
}
return sb.toString();
}
}
将输出:
大小:1
inMemorySize:串的2097384
尺寸:1048576
PS:本ehcache.xml中文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="false" monitoring="autodetect" maxBytesLocalHeap="512M">
<cache name="OneCache"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
memoryStoreEvictionPolicy="LFU">
<sizeOfPolicy maxDepth="10000" maxDepthExceededBehavior="abort"/>
</cache>
</ehcache>
尝试在generateDummyString函数中使用unicode字符。 – sgmoore
@sgmoore刚刚尝试过,没有任何改变。同样如您所见,我检查字符串的大小和内存大小,因此如果字节大小以字节为单位,我会注意到它。 – Flowryn