in commons-jcs3-core/src/main/java/org/apache/commons/jcs3/admin/JCSAdminBean.java [236:299]
public <K, V> long getByteCount(final CompositeCache<K, V> cache)
{
if (cache == null)
{
throw new IllegalArgumentException("The cache object specified was null.");
}
long size = 0;
final IMemoryCache<K, V> memCache = cache.getMemoryCache();
for (final K key : memCache.getKeySet())
{
ICacheElement<K, V> ice = null;
try
{
ice = memCache.get(key);
}
catch (final IOException e)
{
throw new IllegalStateException("IOException while trying to get a cached element", e);
}
if (ice == null)
{
continue;
}
if (ice instanceof CacheElementSerialized)
{
size += ((CacheElementSerialized<K, V>) ice).getSerializedValue().length;
}
else
{
final Object element = ice.getVal();
//CountingOnlyOutputStream: Keeps track of the number of bytes written to it, but doesn't write them anywhere.
final CountingOnlyOutputStream counter = new CountingOnlyOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(counter))
{
out.writeObject(element);
}
catch (final IOException e)
{
throw new IllegalStateException("IOException while trying to measure the size of the cached element", e);
}
finally
{
try
{
counter.close();
}
catch (final IOException e)
{
// ignore
}
}
// 4 bytes lost for the serialization header
size += counter.getCount() - 4;
}
}
return size;
}