1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.pool.sizeof;
18
19 import net.sf.ehcache.pool.sizeof.filter.PassThroughFilter;
20 import net.sf.ehcache.pool.sizeof.filter.SizeOfFilter;
21
22 import static net.sf.ehcache.pool.sizeof.JvmInformation.MINIMUM_OBJECT_SIZE;
23
24 /***
25 * SizeOf implementation that relies on a Java agent to be loaded to do the measurement
26 * It will try to load the agent through the JDK6 Attach API if available
27 * All it's constructor do throw UnsupportedOperationException if the agent isn't present or couldn't be loaded dynamically
28 * @author Chris Dennis
29 * @author Alex Snaps
30 */
31 public class AgentSizeOf extends SizeOf {
32
33 private static final boolean AGENT_LOADED = AgentLoader.loadAgent();
34
35 /***
36 * Builds a new SizeOf that will not filter fields and will cache reflected fields
37 * @throws UnsupportedOperationException If agent couldn't be loaded or isn't present
38 * @see #AgentSizeOf(net.sf.ehcache.pool.sizeof.filter.SizeOfFilter, boolean)
39 */
40 public AgentSizeOf() throws UnsupportedOperationException {
41 this(new PassThroughFilter());
42 }
43
44 /***
45 * Builds a new SizeOf that will filter fields according to the provided filter and will cache reflected fields
46 * @param filter The filter to apply
47 * @throws UnsupportedOperationException If agent couldn't be loaded or isn't present
48 * @see #AgentSizeOf(net.sf.ehcache.pool.sizeof.filter.SizeOfFilter, boolean)
49 * @see SizeOfFilter
50 */
51 public AgentSizeOf(SizeOfFilter filter) throws UnsupportedOperationException {
52 this(filter, true);
53 }
54
55 /***
56 * Builds a new SizeOf that will filter fields according to the provided filter
57 * @param filter The filter to apply
58 * @param caching whether to cache reflected fields
59 * @throws UnsupportedOperationException If agent couldn't be loaded or isn't present
60 * @see SizeOfFilter
61 */
62 public AgentSizeOf(SizeOfFilter filter, boolean caching) throws UnsupportedOperationException {
63 super(filter, caching);
64 if (!AGENT_LOADED) {
65 throw new UnsupportedOperationException("Agent not available or loadable");
66 }
67 }
68
69 @Override
70 protected long measureSizeOf(Object obj) {
71 return Math.max(MINIMUM_OBJECT_SIZE, AgentLoader.agentSizeOf(obj));
72 }
73 }