CacheSizes.java 7.01 KB
Newer Older
1
/**
Matt Tucker's avatar
Matt Tucker committed
2 3 4 5
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
Matt Tucker's avatar
Matt Tucker committed
19 20
 */

21 22 23
package org.jivesoftware.util.cache;

import org.jivesoftware.util.cache.Cacheable;
Matt Tucker's avatar
Matt Tucker committed
24

25 26 27
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
28
import java.util.Collection;
29 30
import java.util.Map;
import java.util.Set;
Matt Tucker's avatar
Matt Tucker committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

/**
 * Utility class for determining the sizes in bytes of commonly used objects.
 * Classes implementing the Cacheable interface should use this class to
 * determine their size.
 *
 * @author Matt Tucker
 */
public class CacheSizes {

    /**
     * Returns the size in bytes of a basic Object. This method should only
     * be used for actual Object objects and not classes that extend Object.
     *
     * @return the size of an Object.
     */
    public static int sizeOfObject() {
        return 4;
    }

    /**
     * Returns the size in bytes of a String.
     *
     * @param string the String to determine the size of.
     * @return the size of a String.
     */
    public static int sizeOfString(String string) {
        if (string == null) {
            return 0;
        }
61
        return 4 + string.getBytes().length;
Matt Tucker's avatar
Matt Tucker committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    }

    /**
     * Returns the size in bytes of a primitive int.
     *
     * @return the size of a primitive int.
     */
    public static int sizeOfInt() {
        return 4;
    }

    /**
     * Returns the size in bytes of a primitive char.
     *
     * @return the size of a primitive char.
     */
    public static int sizeOfChar() {
        return 2;
    }

    /**
     * Returns the size in bytes of a primitive boolean.
     *
     * @return the size of a primitive boolean.
     */
    public static int sizeOfBoolean() {
        return 1;
    }

    /**
     * Returns the size in bytes of a primitive long.
     *
     * @return the size of a primitive long.
     */
    public static int sizeOfLong() {
        return 8;
    }

    /**
     * Returns the size in bytes of a primitive double.
     *
     * @return the size of a primitive double.
     */
    public static int sizeOfDouble() {
        return 8;
    }

    /**
     * Returns the size in bytes of a Date.
     *
     * @return the size of a Date.
     */
    public static int sizeOfDate() {
        return 12;
    }

    /**
119
     * Returns the size in bytes of a Map object. 
Matt Tucker's avatar
Matt Tucker committed
120 121 122 123
     *
     * @param map the Map object to determine the size of.
     * @return the size of the Map object.
     */
124 125
    public static int sizeOfMap(Map map)
	    throws CannotCalculateSizeException {
Matt Tucker's avatar
Matt Tucker committed
126 127 128 129 130
        if (map == null) {
            return 0;
        }
        // Base map object -- should be something around this size.
        int size = 36;
131
		Set<? extends Map.Entry> set = map.entrySet();
132
        
Matt Tucker's avatar
Matt Tucker committed
133
        // Add in size of each value
134 135 136
        for (Map.Entry<Object, Object> entry : set) {
			size += sizeOfAnything(entry.getKey());
            size += sizeOfAnything(entry.getValue());
Matt Tucker's avatar
Matt Tucker committed
137 138 139 140 141
        }
        return size;
    }

    /**
142
     * Returns the size in bytes of a Collection object. Elements are assumed to be
Matt Tucker's avatar
Matt Tucker committed
143 144
     * <tt>String</tt>s, <tt>Long</tt>s or <tt>Cacheable</tt> objects.
     *
145 146
     * @param list the Collection object to determine the size of.
     * @return the size of the Collection object.
Matt Tucker's avatar
Matt Tucker committed
147
     */
148 149
    public static int sizeOfCollection(Collection list) 
            throws CannotCalculateSizeException {
Matt Tucker's avatar
Matt Tucker committed
150 151 152 153 154 155 156 157
        if (list == null) {
            return 0;
        }
        // Base list object (approximate)
        int size = 36;
        // Add in size of each value
        Object[] values = list.toArray();
        for (int i = 0; i < values.length; i++) {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            size += sizeOfAnything(values[i]);
        }
        return size;
    }

    /**
     * Returns the size of an object in bytes. Determining size by serialization
     * is only used as a last resort.
     *
     * @return the size of an object in bytes.
     */
    public static int sizeOfAnything(Object object) 
	    throws CannotCalculateSizeException {
        // If the object is Cacheable, ask it its size.
        if (object == null) {
            return 0;
        }
        if (object instanceof Cacheable) {
            return ((Cacheable)object).getCachedSize();
        }
        // Check for other common types of objects put into cache.
        else if (object instanceof String) {
            return sizeOfString((String)object);
        }
        else if (object instanceof Long) {
            return sizeOfLong();
        }
        else if (object instanceof Integer) {
            return sizeOfObject() + sizeOfInt();
        }
        else if (object instanceof Double) {
            return sizeOfObject() + sizeOfDouble();
        }
        else if (object instanceof Boolean) {
            return sizeOfObject() + sizeOfBoolean();
        }
        else if (object instanceof Map) {
            return sizeOfMap((Map)object);
        }
        else if (object instanceof long[]) {
            long[] array = (long[])object;
            return sizeOfObject() + array.length * sizeOfLong();
        }
        else if (object instanceof Collection) {
            return sizeOfCollection((Collection)object);
        }
        else if (object instanceof byte[]) {
            byte [] array = (byte[])object;
            return sizeOfObject() + array.length;
        }
        // Default behavior -- serialize the object to determine its size.
        else {
            int size = 1;
            try {
                // Default to serializing the object out to determine size.
                CacheSizes.NullOutputStream out = new NullOutputStream();
                ObjectOutputStream outObj = new ObjectOutputStream(out);
                outObj.writeObject(object);
                size = out.size();
Matt Tucker's avatar
Matt Tucker committed
217
            }
218 219
            catch (IOException ioe) {
                throw new CannotCalculateSizeException(object);
Matt Tucker's avatar
Matt Tucker committed
220
            }
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            return size;
        }
    }

    private static class NullOutputStream extends OutputStream {

        int size = 0;

        @Override
        public void write(int b) throws IOException {
            size++;
        }

        @Override
        public void write(byte[] b) throws IOException {
            size += b.length;
        }

        @Override
        public void write(byte[] b, int off, int len) {
            size += len;
        }

        /**
         * Returns the number of bytes written out through the stream.
         *
         * @return the number of bytes written to the stream.
         */
        public int size() {
            return size;
Matt Tucker's avatar
Matt Tucker committed
251 252
        }
    }
253
}