01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18: package org.apache.ivy.util;
19:
20: /**
21: * Memory related utilities.
22: */
23: public final class MemoryUtil {
24: private static final int SAMPLING_SIZE = 100;
25: private static final int SLEEP_TIME = 100;
26:
27: private MemoryUtil() {
28: }
29:
30: /**
31: * Returns the approximate size of a default instance of the given class.
32: *
33: * @param clazz
34: * the class to evaluate.
35: * @return the estimated size of instance, in bytes.
36: */
37: public static long sizeOf(Class clazz) {
38: long size = 0;
39: Object[] objects = new Object[SAMPLING_SIZE];
40: try {
41: clazz.newInstance();
42: long startingMemoryUse = getUsedMemory();
43: for (int i = 0; i < objects.length; i++) {
44: objects[i] = clazz.newInstance();
45: }
46: long endingMemoryUse = getUsedMemory();
47: float approxSize = (endingMemoryUse - startingMemoryUse)
48: / (float) objects.length;
49: size = Math.round(approxSize);
50: } catch (Exception e) {
51: System.out.println("WARNING:couldn't instantiate" + clazz);
52: e.printStackTrace();
53: }
54: return size;
55: }
56:
57: /**
58: * Returns the currently used memory, after calling garbage collector and waiting enough to get
59: * maximal chance it is actually called. But since {@link Runtime#gc()} is only advisory,
60: * results returned by this method should be treated as rough approximation only.
61: *
62: * @return the currently used memory, in bytes.
63: */
64: public static long getUsedMemory() {
65: gc();
66: long totalMemory = Runtime.getRuntime().totalMemory();
67: gc();
68: long freeMemory = Runtime.getRuntime().freeMemory();
69: long usedMemory = totalMemory - freeMemory;
70: return usedMemory;
71: }
72:
73: private static void gc() {
74: try {
75: System.gc();
76: Thread.sleep(SLEEP_TIME);
77: System.runFinalization();
78: Thread.sleep(SLEEP_TIME);
79: System.gc();
80: Thread.sleep(SLEEP_TIME);
81: System.runFinalization();
82: Thread.sleep(SLEEP_TIME);
83: } catch (Exception e) {
84: e.printStackTrace();
85: }
86: }
87:
88: public static void main(String[] args)
89: throws ClassNotFoundException {
90: System.out.println(sizeOf(Class.forName(args[0])));
91: }
92: }
|