2017-01-16 62 views
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> 
+1

尝试在generateDummyString函数中使用unicode字符。 – sgmoore

+0

@sgmoore刚刚尝试过,没有任何改变。同样如您所见,我检查字符串的大小和内存大小,因此如果字节大小以字节为单位,我会注意到它。 – Flowryn

回答

2

字符串在Java中使用双字节字符。 Ehcache没有加倍大小。当你调用toBytes()时,你会得到编码的字节(在这种情况下,使用默认的UTF-8编码)。这就是你看到差异的原因。

+0

谢谢Martin Serrano,我错过了这一点。对Bytes()进行调用,然后存储该项目解决了问题。 – Flowryn

相关问题