View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package org.apache.hadoop.hbase.util;
22  
23  import java.lang.reflect.Field;
24  import java.lang.reflect.Modifier;
25  import java.util.concurrent.ConcurrentHashMap;
26  import java.util.concurrent.ConcurrentSkipListMap;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  
32
33  /**
34   * Class for determining the "size" of a class, an attempt to calculate the
35   * actual bytes that an object of this class will occupy in memory
36   *
37   * The core of this class is taken from the Derby project
38   */
39  @InterfaceAudience.Private
40  public class ClassSize {
41    private static final Log LOG = LogFactory.getLog(ClassSize.class);
42
43    /** Array overhead */
44    public static final int ARRAY;
45
46    /** Overhead for ArrayList(0) */
47    public static final int ARRAYLIST;
48
49    /** Overhead for ByteBuffer */
50    public static final int BYTE_BUFFER;
51
52    /** Overhead for an Integer */
53    public static final int INTEGER;
54
55    /** Overhead for entry in map */
56    public static final int MAP_ENTRY;
57
58    /** Object overhead is minimum 2 * reference size (8 bytes on 64-bit) */
59    public static final int OBJECT;
60
61    /** Reference size is 8 bytes on 64-bit, 4 bytes on 32-bit */
62    public static final int REFERENCE;
63
64    /** String overhead */
65    public static final int STRING;
66
67    /** Overhead for TreeMap */
68    public static final int TREEMAP;
69
70    /** Overhead for ConcurrentHashMap */
71    public static final int CONCURRENT_HASHMAP;
72
73    /** Overhead for ConcurrentHashMap.Entry */
74    public static final int CONCURRENT_HASHMAP_ENTRY;
75
76    /** Overhead for ConcurrentHashMap.Segment */
77    public static final int CONCURRENT_HASHMAP_SEGMENT;
78
79    /** Overhead for ConcurrentSkipListMap */
80    public static final int CONCURRENT_SKIPLISTMAP;
81
82    /** Overhead for ConcurrentSkipListMap Entry */
83    public static final int CONCURRENT_SKIPLISTMAP_ENTRY;
84
85    /** Overhead for CellArrayMap */
86    public static final int CELL_ARRAY_MAP;
87
88    /** Overhead for Cell Array Entry */
89    public static final int CELL_ARRAY_MAP_ENTRY;
90
91    /** Overhead for ReentrantReadWriteLock */
92    public static final int REENTRANT_LOCK;
93
94    /** Overhead for AtomicLong */
95    public static final int ATOMIC_LONG;
96
97    /** Overhead for AtomicInteger */
98    public static final int ATOMIC_INTEGER;
99
100   /** Overhead for AtomicBoolean */
101   public static final int ATOMIC_BOOLEAN;
102
103   /** Overhead for CopyOnWriteArraySet */
104   public static final int COPYONWRITE_ARRAYSET;
105
106   /** Overhead for CopyOnWriteArrayList */
107   public static final int COPYONWRITE_ARRAYLIST;
108
109   /** Overhead for timerange */
110   public static final int TIMERANGE;
111
112   /** Overhead for TimeRangeTracker */
113   public static final int TIMERANGE_TRACKER;
114
115   /** Overhead for CellSkipListSet */
116   public static final int CELL_SET;
117
118   public static final int STORE_SERVICES;
119
120   /* Are we running on jdk7? */
121   private static final boolean JDK7;
122   static {
123     final String version = System.getProperty("java.version");
124     // Verify String looks like this: 1.6.0_29
125     if (version == null || !version.matches("\\d\\.\\d\\..*")) {
126       throw new RuntimeException("Unexpected version format: " + version);
127     }
128     // Convert char to int
129     int major = (int)(version.charAt(0) - '0');
130     int minor = (int)(version.charAt(2) - '0');
131     JDK7 = major == 1 && minor == 7;
132   }
133
134   /**
135    * MemoryLayout abstracts details about the JVM object layout. Default implementation is used in
136    * case Unsafe is not available.
137    */
138   private static class MemoryLayout {
139     int headerSize() {
140       return 2 * oopSize();
141     }
142
143     int arrayHeaderSize() {
144       return (int) align(3 * oopSize());
145     }
146
147     /**
148      * Return the size of an "ordinary object pointer". Either 4 or 8, depending on 32/64 bit,
149      * and CompressedOops
150      */
151     int oopSize() {
152       return is32BitJVM() ? 4 : 8;
153     }
154
155     /**
156      * Aligns a number to 8.
157      * @param num number to align to 8
158      * @return smallest number >= input that is a multiple of 8
159      */
160     public long align(long num) {
161       //The 7 comes from that the alignSize is 8 which is the number of bytes
162       //stored and sent together
163       return  ((num + 7) >> 3) << 3;
164     }
165
166     long sizeOf(byte[] b, int len) {
167       return align(arrayHeaderSize() + len);
168     }
169   }
170
171   /**
172    * UnsafeLayout uses Unsafe to guesstimate the object-layout related parameters like object header
173    * sizes and oop sizes
174    * See HBASE-15950.
175    */
176   private static class UnsafeLayout extends MemoryLayout {
177     @SuppressWarnings("unused")
178     private static final class HeaderSize {
179       private byte a;
180     }
181
182     public UnsafeLayout() {
183     }
184
185     @Override
186     int headerSize() {
187       try {
188         return (int) UnsafeAccess.theUnsafe.objectFieldOffset(
189           HeaderSize.class.getDeclaredField("a"));
190       } catch (NoSuchFieldException | SecurityException e) {
191         LOG.error(e);
192       }
193       return super.headerSize();
194     }
195
196     @Override
197     int arrayHeaderSize() {
198       return UnsafeAccess.theUnsafe.arrayBaseOffset(byte[].class);
199     }
200
201     @Override
202     @SuppressWarnings("static-access")
203     int oopSize() {
204       // Unsafe.addressSize() returns 8, even with CompressedOops. This is how many bytes each
205       // element is allocated in an Object[].
206       return UnsafeAccess.theUnsafe.ARRAY_OBJECT_INDEX_SCALE;
207     }
208
209     @Override
210     @SuppressWarnings("static-access")
211     long sizeOf(byte[] b, int len) {
212       return align(arrayHeaderSize() + len * UnsafeAccess.theUnsafe.ARRAY_BYTE_INDEX_SCALE);
213     }
214   }
215
216   private static MemoryLayout getMemoryLayout() {
217     // Have a safeguard in case Unsafe estimate is wrong. This is static context, there is
218     // no configuration, so we look at System property.
219     String enabled = System.getProperty("hbase.memorylayout.use.unsafe");
220     if (UnsafeAvailChecker.isAvailable() && (enabled == null || Boolean.parseBoolean(enabled))) {
221       LOG.debug("Using Unsafe to estimate memory layout");
222       return new UnsafeLayout();
223     }
224     LOG.debug("Not using Unsafe to estimate memory layout");
225     return new MemoryLayout();
226   }
227
228   private static final MemoryLayout memoryLayout = getMemoryLayout();
229
230   /**
231    * Method for reading the arc settings and setting overheads according
232    * to 32-bit or 64-bit architecture.
233    */
234   static {
235     REFERENCE = memoryLayout.oopSize();
236
237     OBJECT = memoryLayout.headerSize();
238
239     ARRAY = memoryLayout.arrayHeaderSize();
240
241     ARRAYLIST = align(OBJECT + REFERENCE + (2 * Bytes.SIZEOF_INT)) + align(ARRAY);
242
243     //noinspection PointlessArithmeticExpression
244     BYTE_BUFFER = align(OBJECT + REFERENCE +
245         (5 * Bytes.SIZEOF_INT) +
246         (3 * Bytes.SIZEOF_BOOLEAN) + Bytes.SIZEOF_LONG) + align(ARRAY);
247
248     INTEGER = align(OBJECT + Bytes.SIZEOF_INT);
249
250     MAP_ENTRY = align(OBJECT + 5 * REFERENCE + Bytes.SIZEOF_BOOLEAN);
251
252     TREEMAP = align(OBJECT + (2 * Bytes.SIZEOF_INT) + 7 * REFERENCE);
253
254     // STRING is different size in jdk6 and jdk7. Just use what we estimate as size rather than
255     // have a conditional on whether jdk7.
256     STRING = (int) estimateBase(String.class, false);
257
258     // CONCURRENT_HASHMAP is different size in jdk6 and jdk7; it looks like its different between
259     // 23.6-b03 and 23.0-b21. Just use what we estimate as size rather than have a conditional on
260     // whether jdk7.
261     CONCURRENT_HASHMAP = (int) estimateBase(ConcurrentHashMap.class, false);
262
263     CONCURRENT_HASHMAP_ENTRY = align(REFERENCE + OBJECT + (3 * REFERENCE) +
264         (2 * Bytes.SIZEOF_INT));
265
266     CONCURRENT_HASHMAP_SEGMENT = align(REFERENCE + OBJECT +
267         (3 * Bytes.SIZEOF_INT) + Bytes.SIZEOF_FLOAT + ARRAY);
268
269     // The size changes from jdk7 to jdk8, estimate the size rather than use a conditional
270     CONCURRENT_SKIPLISTMAP = (int) estimateBase(ConcurrentSkipListMap.class, false);
271
272     // CELL_ARRAY_MAP is the size of an instance of CellArrayMap class, which extends
273     // CellFlatMap class. CellArrayMap object containing a ref to an Array, so
274     // OBJECT + REFERENCE + ARRAY
275     // CellFlatMap object contains two integers, one boolean and one reference to object, so
276     // 2*INT + BOOLEAN + REFERENCE
277     CELL_ARRAY_MAP = align(OBJECT + 2*Bytes.SIZEOF_INT + Bytes.SIZEOF_BOOLEAN
278         + ARRAY + 2*REFERENCE);
279
280     CONCURRENT_SKIPLISTMAP_ENTRY = align(
281         align(OBJECT + (3 * REFERENCE)) + /* one node per entry */
282         align((OBJECT + (3 * REFERENCE))/2)); /* one index per two entries */
283
284     // REFERENCE in the CellArrayMap all the rest is counted in KeyValue.heapSize()
285     CELL_ARRAY_MAP_ENTRY = align(REFERENCE);
286
287     REENTRANT_LOCK = align(OBJECT + (3 * REFERENCE));
288
289     ATOMIC_LONG = align(OBJECT + Bytes.SIZEOF_LONG);
290
291     ATOMIC_INTEGER = align(OBJECT + Bytes.SIZEOF_INT);
292
293     ATOMIC_BOOLEAN = align(OBJECT + Bytes.SIZEOF_BOOLEAN);
294
295     COPYONWRITE_ARRAYSET = align(OBJECT + REFERENCE);
296
297     COPYONWRITE_ARRAYLIST = align(OBJECT + (2 * REFERENCE) + ARRAY);
298
299     TIMERANGE = align(ClassSize.OBJECT + Bytes.SIZEOF_LONG * 2 + Bytes.SIZEOF_BOOLEAN);
300
301     TIMERANGE_TRACKER = align(ClassSize.OBJECT + Bytes.SIZEOF_LONG * 2);
302
303     CELL_SET = align(OBJECT + REFERENCE);
304
305     STORE_SERVICES = align(OBJECT + REFERENCE + ATOMIC_LONG);
306   }
307
308   /**
309    * The estimate of the size of a class instance depends on whether the JVM
310    * uses 32 or 64 bit addresses, that is it depends on the size of an object
311    * reference. It is a linear function of the size of a reference, e.g.
312    * 24 + 5*r where r is the size of a reference (usually 4 or 8 bytes).
313    *
314    * This method returns the coefficients of the linear function, e.g. {24, 5}
315    * in the above example.
316    *
317    * @param cl A class whose instance size is to be estimated
318    * @param debug debug flag
319    * @return an array of 3 integers. The first integer is the size of the
320    * primitives, the second the number of arrays and the third the number of
321    * references.
322    */
323   @SuppressWarnings("unchecked")
324   private static int [] getSizeCoefficients(Class cl, boolean debug) {
325     int primitives = 0;
326     int arrays = 0;
327     int references = 0;
328     int index = 0;
329
330     for ( ; null != cl; cl = cl.getSuperclass()) {
331       Field[] field = cl.getDeclaredFields();
332       if (null != field) {
333         for (Field aField : field) {
334           if (Modifier.isStatic(aField.getModifiers())) continue;
335           Class fieldClass = aField.getType();
336           if (fieldClass.isArray()) {
337             arrays++;
338             references++;
339           } else if (!fieldClass.isPrimitive()) {
340             references++;
341           } else {// Is simple primitive
342             String name = fieldClass.getName();
343
344             if (name.equals("int") || name.equals("I"))
345               primitives += Bytes.SIZEOF_INT;
346             else if (name.equals("long") || name.equals("J"))
347               primitives += Bytes.SIZEOF_LONG;
348             else if (name.equals("boolean") || name.equals("Z"))
349               primitives += Bytes.SIZEOF_BOOLEAN;
350             else if (name.equals("short") || name.equals("S"))
351               primitives += Bytes.SIZEOF_SHORT;
352             else if (name.equals("byte") || name.equals("B"))
353               primitives += Bytes.SIZEOF_BYTE;
354             else if (name.equals("char") || name.equals("C"))
355               primitives += Bytes.SIZEOF_CHAR;
356             else if (name.equals("float") || name.equals("F"))
357               primitives += Bytes.SIZEOF_FLOAT;
358             else if (name.equals("double") || name.equals("D"))
359               primitives += Bytes.SIZEOF_DOUBLE;
360           }
361           if (debug) {
362             if (LOG.isDebugEnabled()) {
363               LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
364             }
365           }
366           index++;
367         }
368       }
369     }
370     return new int [] {primitives, arrays, references};
371   }
372
373   /**
374    * Estimate the static space taken up by a class instance given the
375    * coefficients returned by getSizeCoefficients.
376    *
377    * @param coeff the coefficients
378    *
379    * @param debug debug flag
380    * @return the size estimate, in bytes
381    */
382   private static long estimateBaseFromCoefficients(int [] coeff, boolean debug) {
383     long prealign_size = OBJECT + coeff[0] + coeff[2] * REFERENCE;
384
385     // Round up to a multiple of 8
386     long size = align(prealign_size) + align(coeff[1] * ARRAY);
387     if (debug) {
388       if (LOG.isDebugEnabled()) {
389         LOG.debug("Primitives=" + coeff[0] + ", arrays=" + coeff[1] +
390             ", references=" + coeff[2] + ", refSize " + REFERENCE +
391             ", size=" + size + ", prealign_size=" + prealign_size);
392       }
393     }
394     return size;
395   }
396
397   /**
398    * Estimate the static space taken up by the fields of a class. This includes
399    * the space taken up by by references (the pointer) but not by the referenced
400    * object. So the estimated size of an array field does not depend on the size
401    * of the array. Similarly the size of an object (reference) field does not
402    * depend on the object.
403    *
404    * @param cl class
405    * @param debug debug flag
406    * @return the size estimate in bytes.
407    */
408   @SuppressWarnings("unchecked")
409   public static long estimateBase(Class cl, boolean debug) {
410     return estimateBaseFromCoefficients( getSizeCoefficients(cl, debug), debug);
411   }
412
413   /**
414    * Aligns a number to 8.
415    * @param num number to align to 8
416    * @return smallest number &gt;= input that is a multiple of 8
417    */
418   public static int align(int num) {
419     return (int)(align((long)num));
420   }
421
422   /**
423    * Aligns a number to 8.
424    * @param num number to align to 8
425    * @return smallest number &gt;= input that is a multiple of 8
426    */
427   public static long align(long num) {
428     return memoryLayout.align(num);
429   }
430
431   /**
432    * Determines if we are running in a 32-bit JVM. Some unit tests need to
433    * know this too.
434    */
435   public static boolean is32BitJVM() {
436     final String model = System.getProperty("sun.arch.data.model");
437     return model != null && model.equals("32");
438   }
439
440   public static long sizeOf(byte[] b, int len) {
441     return memoryLayout.sizeOf(b, len);
442   }
443
444 }
445