com.addthis.basis.util.MemoryCounter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of basis Show documentation
Show all versions of basis Show documentation
AddThis core java classes
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.addthis.basis.util;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* estimates the retained size of an object graph in memory
*/
public final class MemoryCounter {
private static final ConcurrentHashMap, FieldCache[]> fieldCache = new ConcurrentHashMap<>();
private static final Map, MemEstimator> estimators = new IdentityHashMap<>();
private static Instrumentation instrumentation;
private static final int booleanClass = boolean.class.hashCode();
private static final int byteClass = byte.class.hashCode();
private static final int charClass = char.class.hashCode();
private static final int shortClass = short.class.hashCode();
private static final int intClass = int.class.hashCode();
private static final int floatClass = float.class.hashCode();
private static final int doubleClass = double.class.hashCode();
private static final int longClass = long.class.hashCode();
public static void premain(String args, Instrumentation inst) {
System.out.println("using native jvm instrumentation: " + inst);
instrumentation = inst;
}
public static void registerEstimator(Class> clazz, MemEstimator est) {
estimators.put(clazz, est);
}
static {
registerEstimator(String.class, new StringEstimator());
}
/**
* control sizing estimation
*/
@Retention(RetentionPolicy.RUNTIME)
public static @interface Mem {
boolean estimate() default true;
int size() default -1;
}
public static interface MemEstimator {
public long getMemorySize(Object object);
}
public static class StringEstimator implements MemEstimator {
private static final long base_size = estimateSize(new String(""));
@Override
public long getMemorySize(Object object) {
return base_size + (((String) object).length() * 2);
}
}
private final Map