├── .gitignore ├── Jenkinsfile ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── objectexplorer │ │ ├── Chain.java │ │ ├── InstrumentationGrabber.java │ │ ├── MemoryMeasurer.java │ │ ├── ObjectExplorer.java │ │ ├── ObjectGraphMeasurer.java │ │ ├── ObjectSerializer.java │ │ └── ObjectVisitor.java └── resources │ └── META-INF │ └── MANIFEST.MF └── test └── java ├── memorymeasurer └── ElementCostOfDataStructures.java └── objectexplorer └── ObjectSerializerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | /target/ 4 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | node { 2 | def mvnHome = tool 'M3' 3 | env.JAVA_HOME="${tool 'jdk-oracle-8'}" 4 | env.PATH="${env.JAVA_HOME}/bin:${mvnHome}/bin:${env.PATH}" 5 | 6 | stage 'Clone' 7 | checkout scm 8 | 9 | stage 'Build and Test' 10 | sh "mvn -B clean install" 11 | 12 | stage 'Deploy' 13 | sh "mvn -s ${env.HOME}/usethesource-maven-settings.xml -B deploy" 14 | 15 | stage 'Archive' 16 | step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true]) 17 | step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml']) 18 | } 19 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2009] [Dimitrios Andreou] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ObjectExplorer 2 | 3 | Originally authored by Dimitris Andreou (jim.andreou@gmail.com). 4 | 5 | See package javadocs for information. 6 | 7 | Quick tip: To use the MemoryMeasurer (to measure the footprint of an object 8 | graph in bytes), this parameter needs to be passed to th VM: 9 | -javaagent:path/to/object-explorer.jar 10 | 11 | # Origin 12 | 13 | This library was forked when it used to exist on Google Code only. In the meantime the original author moved the code to github as well ([DimitrisAndreou/memory-measurer](https://github.com/DimitrisAndreou/memory-measurer)), however it appears that the library is not actively maintained any more. 14 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | com.github.msteindorfer 5 | memory-measurer 6 | 0.1.0-SNAPSHOT 7 | jar 8 | 9 | 10 | scm:git:https://github.com/msteindorfer/memory-measurer.git 11 | HEAD 12 | 13 | 14 | 15 | 16 | 17 | usethesource-releases 18 | http://nexus.rascal-mpl.org/repository/maven-releases/ 19 | 20 | 21 | usethesource-snapshots 22 | http://nexus.rascal-mpl.org/repository/maven-snapshots/ 23 | 24 | 25 | 26 | 27 | 28 | 29 | usethesource 30 | http://nexus.rascal-mpl.org/repository/maven-public/ 31 | 32 | 33 | 34 | 35 | UTF-8 36 | 1.8 37 | 1.8 38 | 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-jar-plugin 45 | 3.0.2 46 | 47 | 48 | 49 | objectexplorer.InstrumentationGrabber 50 | 51 | 52 | 57 | 60 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | com.google.guava 72 | guava 73 | r09 74 | 75 | 76 | com.google.code.findbugs 77 | jsr305 78 | 3.0.1 79 | 80 | 81 | 82 | 83 | junit 84 | junit 85 | 4.11 86 | test 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/Chain.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import com.google.common.base.Preconditions; 4 | import java.lang.reflect.Field; 5 | import java.util.ArrayDeque; 6 | import java.util.Deque; 7 | import java.util.Iterator; 8 | import javax.annotation.Nonnull; 9 | import javax.annotation.Nullable; 10 | 11 | /** 12 | * A chain of references, which starts at a root object and leads to a 13 | * particular value (either an object or a primitive). 14 | * 15 | * @author andreou 16 | */ 17 | public abstract class Chain { 18 | private final Object value; 19 | private final Chain parent; 20 | 21 | Chain(Chain parent, Object value) { 22 | this.parent = parent; 23 | this.value = value; 24 | } 25 | 26 | static Chain root(Object value) { 27 | return new Chain(null, Preconditions.checkNotNull(value)) { 28 | @Override 29 | public Class getValueType() { 30 | return getValue().getClass(); 31 | } 32 | }; 33 | } 34 | 35 | FieldChain appendField(Field field, Object value) { 36 | return new FieldChain(this, Preconditions.checkNotNull(field), value); 37 | } 38 | 39 | ArrayIndexChain appendArrayIndex(int arrayIndex, Object value) { 40 | return new ArrayIndexChain(this, arrayIndex, value); 41 | } 42 | 43 | /** 44 | * Returns whether this chain has a parent. This returns false only when 45 | * this chain represents the root object itself. 46 | */ 47 | public boolean hasParent() { 48 | return parent != null; 49 | } 50 | 51 | /** 52 | * Returns the parent chain, from which this chain was created. 53 | * @throws IllegalStateException if {@code !hasParent()}, then an 54 | */ 55 | public @Nonnull Chain getParent() { 56 | Preconditions.checkState(parent != null, "This is the root value, it has no parent"); 57 | return parent; 58 | } 59 | 60 | /** 61 | * Returns the value that this chain leads to. If the value is a primitive, 62 | * a wrapper object is returned instead. 63 | */ 64 | public @Nullable Object getValue() { 65 | return value; 66 | } 67 | 68 | public abstract @Nonnull Class getValueType(); 69 | 70 | /** 71 | * Returns whether the connection of the parent chain and this chain is 72 | * through a field (of the getParent().getValue().getClass() class). 73 | */ 74 | public boolean isThroughField() { 75 | return false; 76 | } 77 | 78 | /** 79 | * Returns whether the connection of the parent chain and this chain is 80 | * through an array index, i.e. the parent leads to an array, and this 81 | * chain leads to an element of that array. 82 | */ 83 | public boolean isThroughArrayIndex() { 84 | return false; 85 | } 86 | 87 | /** 88 | * Returns whether the value of this chain represents a primitive. 89 | */ 90 | public boolean isPrimitive() { 91 | return getValueType().isPrimitive(); 92 | } 93 | 94 | /** 95 | * Returns the root object of this chain. 96 | */ 97 | public @Nonnull Object getRoot() { 98 | Chain current = this; 99 | while (current.hasParent()) { 100 | current = current.getParent(); 101 | } 102 | return current.getValue(); 103 | } 104 | 105 | Deque reverse() { 106 | Deque reverseChain = new ArrayDeque(8); 107 | Chain current = this; 108 | reverseChain.addFirst(current); 109 | while (current.hasParent()) { 110 | current = current.getParent(); 111 | reverseChain.addFirst(current); 112 | } 113 | return reverseChain; 114 | } 115 | 116 | @Override public String toString() { 117 | StringBuilder sb = new StringBuilder(32); 118 | 119 | Iterator it = reverse().iterator(); 120 | // sb.append(it.next().getValue()); 121 | it.next(); sb.append("rootObject"); 122 | while (it.hasNext()) { 123 | sb.append("->"); 124 | Chain current = it.next(); 125 | if (current.isThroughField()) { 126 | sb.append(((FieldChain)current).getField().getName()); 127 | } else if (current.isThroughArrayIndex()) { 128 | sb.append("[").append(((ArrayIndexChain)current).getArrayIndex()).append("]"); 129 | } 130 | } 131 | return sb.toString(); 132 | } 133 | 134 | /* 135 | * Does reuse an existing StringBuffer instead of allocating a new one 136 | */ 137 | public void toString(StringBuffer sb) { 138 | Iterator it = reverse().iterator(); 139 | // sb.append(it.next().getValue()); 140 | it.next(); sb.append("rootObject"); 141 | while (it.hasNext()) { 142 | sb.append("->"); 143 | Chain current = it.next(); 144 | if (current.isThroughField()) { 145 | sb.append(((FieldChain)current).getField().getName()); 146 | } else if (current.isThroughArrayIndex()) { 147 | sb.append("[").append(((ArrayIndexChain)current).getArrayIndex()).append("]"); 148 | } 149 | } 150 | } 151 | 152 | static class FieldChain extends Chain { 153 | private final Field field; 154 | 155 | FieldChain(Chain parent, Field referringField, Object value) { 156 | super(parent, value); 157 | this.field = referringField; 158 | } 159 | 160 | @Override 161 | public boolean isThroughField() { 162 | return true; 163 | } 164 | 165 | @Override 166 | public boolean isThroughArrayIndex() { 167 | return false; 168 | } 169 | 170 | @Override 171 | public Class getValueType() { 172 | return field.getType(); 173 | } 174 | 175 | public Field getField() { 176 | return field; 177 | } 178 | } 179 | 180 | static class ArrayIndexChain extends Chain { 181 | private final int index; 182 | 183 | ArrayIndexChain(Chain parent, int index, Object value) { 184 | super(parent, value); 185 | this.index = index; 186 | } 187 | 188 | @Override 189 | public boolean isThroughField() { 190 | return false; 191 | } 192 | 193 | @Override 194 | public boolean isThroughArrayIndex() { 195 | return true; 196 | } 197 | 198 | @Override 199 | public Class getValueType() { 200 | return getParent().getValue().getClass().getComponentType(); 201 | } 202 | 203 | public int getArrayIndex() { 204 | return index; 205 | } 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/InstrumentationGrabber.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import com.google.common.base.Preconditions; 4 | import java.lang.instrument.Instrumentation; 5 | 6 | /** 7 | * Agent call-back that stores the {@link Instrumentation} provided by the JVM. 8 | * 9 | *

Not to be used directly. 10 | */ 11 | public class InstrumentationGrabber { 12 | private static volatile Instrumentation instrumentation; 13 | 14 | public static void premain(String agentArgs, Instrumentation inst) { 15 | if (InstrumentationGrabber.instrumentation != null) throw new AssertionError("Already initialized"); 16 | InstrumentationGrabber.instrumentation = inst; 17 | } 18 | 19 | private static void checkSetup() { 20 | Preconditions.checkState(instrumentation != null, "Instrumentation is not setup properly. " 21 | + "You have to pass -javaagent:path/to/object-explorer.jar to the java interpreter"); 22 | } 23 | 24 | static Instrumentation instrumentation() { 25 | checkSetup(); 26 | return instrumentation; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/MemoryMeasurer.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.google.common.base.Predicate; 5 | import com.google.common.base.Predicates; 6 | import com.google.common.collect.ImmutableList; 7 | 8 | import java.lang.instrument.Instrumentation; 9 | 10 | /** 11 | * A utility that can be used to measure the memory footprint of an arbitrary 12 | * object graph. In a nutshell, the user gives a root object, and this class 13 | * recursively and reflectively explores the object's references. 14 | * 15 | *

This class can only be used if the containing jar has been given to the 16 | * Java VM as an agent, as follows: 17 | * {@code -javaagent:path/to/object-explorer.jar} 18 | * 19 | * @see #measureBytes(Object) 20 | * @see #measureBytes(Object, Predicate) 21 | */ 22 | public class MemoryMeasurer { 23 | private static final Instrumentation instrumentation = 24 | InstrumentationGrabber.instrumentation(); 25 | 26 | /* 27 | * The bare minimum memory footprint of an enum value, measured empirically. 28 | * This should be subtracted for any enum value encountered, since it 29 | * is static in nature. 30 | */ 31 | private static final long costOfBareEnumConstant = 32 | instrumentation.getObjectSize(DummyEnum.CONSTANT); 33 | 34 | private enum DummyEnum { 35 | CONSTANT; 36 | } 37 | 38 | /** 39 | * Measures the memory footprint, in bytes, of an object graph. The object 40 | * graph is defined by a root object and whatever object can be reached 41 | * through that, excluding static fields, {@code Class} objects, and 42 | * fields defined in {@code enum}s (all these are considered shared values, 43 | * which should not contribute to the cost of any single object graph). 44 | * 45 | *

Equivalent to {@code measureBytes(rootObject, 46 | * Predicates.alwaysTrue())}. 47 | * 48 | * @param rootObject the root object that defines the object graph to be 49 | * measured 50 | * @return the memory footprint, in bytes, of the object graph 51 | */ 52 | public static long measureBytes(Object rootObject) { 53 | return measureBytes(rootObject, Predicates.alwaysTrue()); 54 | } 55 | 56 | /** 57 | * Measures the memory footprint, in bytes, of an object graph. The object 58 | * graph is defined by a root object and whatever object can be reached 59 | * through that, excluding static fields, {@code Class} objects, and 60 | * fields defined in {@code enum}s (all these are considered shared values, 61 | * which should not contribute to the cost of any single object graph), and 62 | * any object for which the user-provided predicate returns {@code false}. 63 | * 64 | * @param rootObject the root object that defines the object graph to be 65 | * measured 66 | * @param objectAcceptor a predicate that returns {@code true} for objects 67 | * to be explored (and treated as part of the object graph), or 68 | * {@code false} to forbid the traversal to traverse the given object 69 | * @return the memory footprint, in bytes, of the object graph 70 | */ 71 | public static long measureBytes(Object rootObject, Predicate objectAcceptor) { 72 | Preconditions.checkNotNull(objectAcceptor, "predicate"); 73 | 74 | Predicate completePredicate = Predicates.and(ImmutableList.of( 75 | new ObjectExplorer.AtMostOncePredicate(), 76 | ObjectExplorer.notEnumFieldsOrClasses, 77 | Predicates.compose(objectAcceptor, ObjectExplorer.chainToObject) 78 | )); 79 | 80 | return ObjectExplorer.exploreObject(rootObject, 81 | new MemoryMeasurerVisitor(completePredicate)); 82 | } 83 | 84 | private static class MemoryMeasurerVisitor implements ObjectVisitor { 85 | private long memory; 86 | private final Predicate predicate; 87 | 88 | MemoryMeasurerVisitor(Predicate predicate) { 89 | this.predicate = predicate; 90 | } 91 | 92 | public Traversal visit(Chain chain) { 93 | if (predicate.apply(chain)) { 94 | Object o = chain.getValue(); 95 | memory += instrumentation.getObjectSize(o); 96 | if (Enum.class.isAssignableFrom(o.getClass())) { 97 | memory -= costOfBareEnumConstant; 98 | } 99 | return Traversal.EXPLORE; 100 | } 101 | return Traversal.SKIP; 102 | } 103 | 104 | public Long result() { 105 | return memory; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/ObjectExplorer.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import objectexplorer.Chain.FieldChain; 4 | import objectexplorer.ObjectVisitor.Traversal; 5 | 6 | import com.google.common.base.Function; 7 | import com.google.common.base.Predicate; 8 | import com.google.common.collect.Lists; 9 | 10 | import java.lang.reflect.AccessibleObject; 11 | import java.lang.reflect.Array; 12 | import java.lang.reflect.Field; 13 | import java.lang.reflect.Modifier; 14 | import java.util.ArrayDeque; 15 | import java.util.Arrays; 16 | import java.util.Collections; 17 | import java.util.Deque; 18 | import java.util.EnumSet; 19 | import java.util.IdentityHashMap; 20 | import java.util.List; 21 | import java.util.Set; 22 | 23 | import javax.annotation.Nonnull; 24 | import java.lang.reflect.Field; 25 | import java.lang.reflect.Modifier; 26 | 27 | /** 28 | * A depth-first object graph explorer. The traversal starts at a root (an 29 | * {@code Object}) and explores any other reachable object (recursively) or 30 | * primitive value, excluding static fields from the traversal. The traversal 31 | * is controlled by a user-supplied {@link ObjectVisitor}, which decides for 32 | * each explored path whether to continue exploration of that path, and it can 33 | * also return a value at the end of the traversal. 34 | */ 35 | public class ObjectExplorer { 36 | private ObjectExplorer() { } 37 | 38 | /** 39 | * Explores an object graph (defined by a root object and whatever is 40 | * reachable through it, following non-static fields) while using an 41 | * {@link ObjectVisitor} to both control the traversal and return a value. 42 | * 43 | *

Equivalent to {@code exploreObject(rootObject, visitor, 44 | * EnumSet.noneOf(Feature.class))}. 45 | * 46 | * @param the type of the value obtained (after the traversal) by the 47 | * ObjectVisitor 48 | * @param rootObject an object to be recursively explored 49 | * @param visitor a visitor that is notified for each explored path and 50 | * decides whether to continue exploration of that path, and constructs a 51 | * return value at the end of the exploration 52 | * @return whatever value is returned by the visitor at the end of the 53 | * traversal 54 | * @see ObjectVisitor 55 | */ 56 | public static T exploreObject(Object rootObject, ObjectVisitor visitor) { 57 | return exploreObject(rootObject, visitor, EnumSet.noneOf(Feature.class)); 58 | } 59 | 60 | /** 61 | * Explores an object graph (defined by a root object and whatever is 62 | * reachable through it, following non-static fields) while using an 63 | * {@link ObjectVisitor} to both control the traversal and return a value. 64 | * 65 | *

The {@code features} further customizes the exploration behavior. 66 | * In particular: 67 | *

    68 | *
  • If {@link Feature#VISIT_PRIMITIVES} is contained in features, 69 | * the visitor will also be notified about exploration of primitive values. 70 | *
  • If {@link Feature#VISIT_NULL} is contained in features, the visitor 71 | * will also be notified about exploration of {@code null} values. 72 | *
73 | * In both cases above, the return value of 74 | * {@link ObjectVisitor#visit(Chain)} is ignored, since neither primitive 75 | * values or {@code null} can be further explored. 76 | * 77 | * @param the type of the value obtained (after the traversal) by the 78 | * ObjectVisitor 79 | * @param rootObject an object to be recursively explored 80 | * @param visitor a visitor that is notified for each explored path 81 | * and decides whether to continue exploration of that path, and constructs 82 | * a return value at the end of the exploration 83 | * @param features a set of desired features that the object exploration should have 84 | * @return whatever value is returned by the visitor at the end of the traversal 85 | * @see ObjectVisitor 86 | */ 87 | public static T exploreObject(Object rootObject, 88 | ObjectVisitor visitor, EnumSet features) { 89 | Deque stack = new ArrayDeque(32); 90 | if (rootObject != null) stack.push(Chain.root(rootObject)); 91 | 92 | while (!stack.isEmpty()) { 93 | Chain chain = stack.pop(); 94 | //the only place where the return value of visit() is considered 95 | Traversal traversal = visitor.visit(chain); 96 | switch (traversal) { 97 | case SKIP: continue; 98 | case EXPLORE: break; 99 | } 100 | 101 | //only nonnull values pushed in the stack 102 | @Nonnull Object value = chain.getValue(); 103 | Class valueClass = value.getClass(); 104 | if (valueClass.isArray()) { 105 | boolean isPrimitive = valueClass.getComponentType().isPrimitive(); 106 | for (int i = Array.getLength(value) - 1; i >= 0; i--) { 107 | Object childValue = Array.get(value, i); 108 | if (isPrimitive) { 109 | if (features.contains(Feature.VISIT_PRIMITIVES)) 110 | visitor.visit(chain.appendArrayIndex(i, childValue)); 111 | continue; 112 | } 113 | if (childValue == null) { 114 | if (features.contains(Feature.VISIT_NULL)) 115 | visitor.visit(chain.appendArrayIndex(i, childValue)); 116 | continue; 117 | } 118 | stack.push(chain.appendArrayIndex(i, childValue)); 119 | } 120 | } else { 121 | for (Field field : getAllFields(value)) { 122 | if (Modifier.isStatic(field.getModifiers())) continue; 123 | Object childValue = null; 124 | try { 125 | childValue = field.get(value); 126 | } catch (Exception e) { 127 | throw new AssertionError(e); 128 | } 129 | if (childValue == null) { 130 | if (features.contains(Feature.VISIT_NULL)) 131 | visitor.visit(chain.appendField(field, childValue)); 132 | continue; 133 | } 134 | boolean isPrimitive = field.getType().isPrimitive(); 135 | Chain extendedChain = chain.appendField(field, childValue); 136 | if (isPrimitive) { 137 | if (features.contains(Feature.VISIT_PRIMITIVES)) 138 | visitor.visit(extendedChain); 139 | continue; 140 | } else { 141 | stack.push(extendedChain); 142 | } 143 | } 144 | } 145 | } 146 | return visitor.result(); 147 | } 148 | 149 | public static class AtMostOncePredicate implements Predicate { 150 | private final Set interner = Collections.newSetFromMap( 151 | new IdentityHashMap()); 152 | 153 | public boolean apply(Chain chain) { 154 | Object o = chain.getValue(); 155 | return o instanceof Class || interner.add(o); 156 | } 157 | } 158 | 159 | static final Predicate notEnumFieldsOrClasses = new Predicate(){ 160 | public boolean apply(Chain chain) { 161 | return !(Enum.class.isAssignableFrom(chain.getValueType()) 162 | || chain.getValue() instanceof Class); 163 | } 164 | }; 165 | 166 | static final Predicate skipTransientFields = new Predicate(){ 167 | public boolean apply(Chain chain) { 168 | if (chain instanceof FieldChain && (((FieldChain) chain).getField().getModifiers() & Modifier.TRANSIENT) != 0) { 169 | return false; 170 | } else { 171 | return true; 172 | } 173 | } 174 | }; 175 | 176 | static final Function chainToObject = 177 | new Function() { 178 | public Object apply(Chain chain) { 179 | return chain.getValue(); 180 | } 181 | }; 182 | 183 | private static Iterable getAllFields(Object o) { 184 | List fields = Lists.newArrayListWithCapacity(8); 185 | Class clazz = o.getClass(); 186 | while (clazz != null) { 187 | fields.addAll(Arrays.asList(clazz.getDeclaredFields())); 188 | clazz = clazz.getSuperclass(); 189 | } 190 | 191 | //all together so there is only one security check 192 | AccessibleObject.setAccessible(fields.toArray(new AccessibleObject[fields.size()]), true); 193 | return fields; 194 | } 195 | 196 | /** 197 | * Enumeration of features that may be optionally requested for an object 198 | * traversal. 199 | * 200 | * @see ObjectExplorer#exploreObject(Object, ObjectVisitor, EnumSet) 201 | */ 202 | public enum Feature { 203 | /** 204 | * Null references should be visited. 205 | */ 206 | VISIT_NULL, 207 | 208 | /** 209 | * Primitive values should be visited. 210 | */ 211 | VISIT_PRIMITIVES 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/ObjectGraphMeasurer.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import objectexplorer.ObjectExplorer.Feature; 4 | import com.google.common.base.Objects; 5 | import com.google.common.base.Preconditions; 6 | import com.google.common.base.Predicate; 7 | import com.google.common.base.Predicates; 8 | import com.google.common.collect.HashMultiset; 9 | import com.google.common.collect.ImmutableList; 10 | import com.google.common.collect.ImmutableMultiset; 11 | import com.google.common.collect.ImmutableSet; 12 | import com.google.common.collect.Multiset; 13 | 14 | import java.util.EnumSet; 15 | 16 | /** 17 | * A tool that can qualitatively measure the footprint 18 | * ({@literal e.g.}, number of objects, references, 19 | * primitives) of a graph structure. 20 | */ 21 | public class ObjectGraphMeasurer { 22 | /** 23 | * The footprint of an object graph. 24 | */ 25 | public static class Footprint { 26 | private final int objects; 27 | private final int references; 28 | private final ImmutableMultiset> primitives; 29 | 30 | private static final ImmutableSet> primitiveTypes = ImmutableSet.>of( 31 | boolean.class, byte.class, char.class, short.class, 32 | int.class, float.class, long.class, double.class); 33 | 34 | /** 35 | * Constructs a Footprint, by specifying the number of objects, 36 | * references, and primitives (represented as a {@link Multiset}). 37 | * 38 | * @param objects the number of objects 39 | * @param references the number of references 40 | * @param primitives the number of primitives (represented by the 41 | * respective primitive classes, e.g. {@code int.class} etc) 42 | */ 43 | public Footprint(int objects, int references, Multiset> primitives) { 44 | Preconditions.checkArgument(objects >= 0, "Negative number of objects"); 45 | Preconditions.checkArgument(references >= 0, "Negative number of references"); 46 | Preconditions.checkArgument(primitiveTypes.containsAll(primitives.elementSet()), 47 | "Unexpected primitive type"); 48 | this.objects = objects; 49 | this.references = references; 50 | this.primitives = ImmutableMultiset.copyOf(primitives); 51 | } 52 | 53 | /** 54 | * Returns the number of objects of this footprint. 55 | */ 56 | public int getObjects() { 57 | return objects; 58 | } 59 | 60 | /** 61 | * Returns the number of references of this footprint. 62 | */ 63 | public int getReferences() { 64 | return references; 65 | } 66 | 67 | /** 68 | * Returns the number of primitives of this footprint 69 | * (represented by the respective primitive classes, 70 | * {@literal e.g.} {@code int.class} etc). 71 | */ 72 | public ImmutableMultiset> getPrimitives() { 73 | return primitives; 74 | } 75 | 76 | @Override 77 | public String toString() { 78 | return Objects.toStringHelper(this) 79 | .add("Objects", objects) 80 | .add("References", references) 81 | .add("Primitives", primitives) 82 | .toString(); 83 | } 84 | } 85 | 86 | /** 87 | * Measures the footprint of the specified object graph. 88 | * The object graph is defined by a root object and whatever object can be 89 | * reached through that, excluding static fields, {@code Class} objects, 90 | * and fields defined in {@code enum}s (all these are considered shared 91 | * values, which should not contribute to the cost of any single object 92 | * graph). 93 | * 94 | *

Equivalent to {@code measure(rootObject, Predicates.alwaysTrue())}. 95 | * 96 | * @param rootObject the root object of the object graph 97 | * @return the footprint of the object graph 98 | */ 99 | public static Footprint measure(Object rootObject) { 100 | return measure(rootObject, Predicates.alwaysTrue()); 101 | } 102 | 103 | /** 104 | * Measures the footprint of the specified object graph. 105 | * The object graph is defined by a root object and whatever object can be 106 | * reached through that, excluding static fields, {@code Class} objects, 107 | * and fields defined in {@code enum}s (all these are considered shared 108 | * values, which should not contribute to the cost of any single object 109 | * graph), and any object for which the user-provided predicate returns 110 | * {@code false}. 111 | * 112 | * @param rootObject the root object of the object graph 113 | * @param objectAcceptor a predicate that returns {@code true} for objects 114 | * to be explored (and treated as part of the footprint), or {@code false} 115 | * to forbid the traversal to traverse the given object 116 | * @return the footprint of the object graph 117 | */ 118 | public static Footprint measure(Object rootObject, Predicate objectAcceptor) { 119 | Preconditions.checkNotNull(objectAcceptor, "predicate"); 120 | 121 | Predicate completePredicate = Predicates.and(ImmutableList.of( 122 | ObjectExplorer.notEnumFieldsOrClasses, 123 | Predicates.compose(objectAcceptor, ObjectExplorer.chainToObject), 124 | new ObjectExplorer.AtMostOncePredicate() 125 | )); 126 | 127 | return ObjectExplorer.exploreObject(rootObject, new ObjectGraphVisitor(completePredicate), 128 | EnumSet.of(Feature.VISIT_PRIMITIVES, Feature.VISIT_NULL)); 129 | } 130 | 131 | private static class ObjectGraphVisitor implements ObjectVisitor { 132 | private int objects; 133 | // -1 to account for the root, which has no reference leading to it 134 | private int references = -1; 135 | private final Multiset> primitives = HashMultiset.create(); 136 | private final Predicate predicate; 137 | 138 | ObjectGraphVisitor(Predicate predicate) { 139 | this.predicate = predicate; 140 | } 141 | 142 | public Traversal visit(Chain chain) { 143 | if (chain.isPrimitive()) { 144 | primitives.add(chain.getValueType()); 145 | return Traversal.SKIP; 146 | } else { 147 | references++; 148 | } 149 | if (predicate.apply(chain) && chain.getValue() != null) { 150 | objects++; 151 | return Traversal.EXPLORE; 152 | } 153 | return Traversal.SKIP; 154 | } 155 | 156 | public Footprint result() { 157 | return new Footprint(objects, references, ImmutableMultiset.copyOf(primitives)); 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/ObjectSerializer.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.EnumSet; 5 | 6 | import objectexplorer.ObjectExplorer.Feature; 7 | 8 | import com.google.common.base.Preconditions; 9 | import com.google.common.base.Predicate; 10 | import com.google.common.base.Predicates; 11 | import com.google.common.collect.ImmutableList; 12 | 13 | /** 14 | * A tool that can qualitatively measure the footprint ({@literal e.g.}, number 15 | * of objects, references, primitives) of a graph structure. 16 | */ 17 | public class ObjectSerializer { 18 | 19 | /** 20 | * Measures the footprint of the specified object graph. The object graph is 21 | * defined by a root object and whatever object can be reached through that, 22 | * excluding static fields, {@code Class} objects, and fields defined in 23 | * {@code enum}s (all these are considered shared values, which should not 24 | * contribute to the cost of any single object graph). 25 | *

26 | * Equivalent to {@code measure(rootObject, Predicates.alwaysTrue())}. 27 | * 28 | * @param rootObject 29 | * the root object of the object graph 30 | * @return the footprint of the object graph 31 | */ 32 | public static String measure(Object rootObject) { 33 | return measure(rootObject, Predicates.alwaysTrue()); 34 | } 35 | 36 | /** 37 | * Measures the footprint of the specified object graph. The object graph is 38 | * defined by a root object and whatever object can be reached through that, 39 | * excluding static fields, {@code Class} objects, and fields defined in 40 | * {@code enum}s (all these are considered shared values, which should not 41 | * contribute to the cost of any single object graph), and any object for 42 | * which the user-provided predicate returns {@code false}. 43 | * 44 | * @param rootObject 45 | * the root object of the object graph 46 | * @param objectAcceptor 47 | * a predicate that returns {@code true} for objects to be 48 | * explored (and treated as part of the footprint), or 49 | * {@code false} to forbid the traversal to traverse the given 50 | * object 51 | * @return the footprint of the object graph 52 | */ 53 | public static String measure(Object rootObject, Predicate objectAcceptor) { 54 | Preconditions.checkNotNull(objectAcceptor, "predicate"); 55 | 56 | Predicate completePredicate = Predicates.and(ImmutableList.of( 57 | ObjectExplorer.notEnumFieldsOrClasses, 58 | Predicates.compose(objectAcceptor, ObjectExplorer.chainToObject), 59 | // ObjectExplorer.skipTransientFields, 60 | new ObjectExplorer.AtMostOncePredicate())); 61 | 62 | return ObjectExplorer.exploreObject(rootObject, new ObjectGraphVisitor(completePredicate), 63 | EnumSet.of(Feature.VISIT_PRIMITIVES, Feature.VISIT_NULL)); 64 | } 65 | 66 | private static class ObjectGraphVisitor implements ObjectVisitor { 67 | private final Predicate predicate; 68 | private final StringBuffer sb = new StringBuffer(32); 69 | 70 | ObjectGraphVisitor(Predicate predicate) { 71 | this.predicate = predicate; 72 | } 73 | 74 | public Traversal visit(Chain chain) { 75 | if (chain.isPrimitive()) { 76 | chain.toString(sb); 77 | sb.append(": "); 78 | sb.append(chain.getValue().toString()); 79 | sb.append("\n"); 80 | return Traversal.SKIP; 81 | } else if (predicate.apply(chain)) { 82 | Object value = chain.getValue(); 83 | 84 | if (value != null) { 85 | chain.toString(sb); 86 | sb.append(": "); 87 | sb.append(value.getClass().toString()); 88 | 89 | if (value.getClass().isArray()) { 90 | int arrayLength = Array.getLength(value); 91 | sb.append(", length = "); 92 | sb.append(arrayLength); 93 | } 94 | 95 | sb.append("\n"); 96 | 97 | return Traversal.EXPLORE; 98 | } else { 99 | chain.toString(sb); 100 | sb.append(": "); 101 | sb.append("null"); 102 | sb.append("\n"); 103 | 104 | return Traversal.SKIP; 105 | } 106 | } else { 107 | return Traversal.SKIP; 108 | } 109 | } 110 | 111 | public String result() { 112 | return sb.toString(); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/objectexplorer/ObjectVisitor.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | /** 4 | * A visitor that controls an object traversal. Implementations 5 | * of this interface are passed to {@link ObjectExplorer} exploration methods. 6 | * 7 | * @param the type of the result that this visitor returns 8 | * (can be defined as {@code Void} to denote no result}. 9 | * @see ObjectExplorer 10 | */ 11 | public interface ObjectVisitor { 12 | /** 13 | * Visits an explored value (the whole chain from the root object 14 | * leading to the value is provided), and decides whether to continue 15 | * the exploration of that value. 16 | * 17 | *

In case the explored value is either primitive or {@code null} 18 | * (e.g., if {@code chain.isPrimitive() || chain.getValue() == null}), 19 | * the return value is meaningless and is ignored. 20 | * 21 | * @param chain the chain that leads to the explored value. 22 | * @return {@link Traversal#EXPLORE} to denote that the visited object 23 | * should be further explored, or {@link Traversal#SKIP} to avoid 24 | * exploring it. 25 | */ 26 | Traversal visit(Chain chain); 27 | 28 | /** 29 | * Returns an arbitrary value (presumably constructed during the object 30 | * graph traversal). 31 | */ 32 | T result(); 33 | 34 | /** 35 | * Constants that denote how the traversal of a given object (chain) 36 | * should continue. 37 | */ 38 | enum Traversal { 39 | /** 40 | * The visited object should be further explored. 41 | */ 42 | EXPLORE, 43 | 44 | /** 45 | * The visited object should not be explored. 46 | */ 47 | SKIP 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Premain-Class: objectexplorer.InstrumentationGrabber -------------------------------------------------------------------------------- /src/test/java/memorymeasurer/ElementCostOfDataStructures.java: -------------------------------------------------------------------------------- 1 | package memorymeasurer; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.base.Preconditions; 5 | import com.google.common.base.Predicate; 6 | import com.google.common.base.Predicates; 7 | import com.google.common.base.Supplier; 8 | import com.google.common.base.Throwables; 9 | import com.google.common.collect.ArrayListMultimap; 10 | import com.google.common.collect.ConcurrentHashMultiset; 11 | import com.google.common.collect.HashBasedTable; 12 | import com.google.common.collect.HashBiMap; 13 | import com.google.common.collect.HashMultimap; 14 | import com.google.common.collect.HashMultiset; 15 | import com.google.common.collect.ImmutableBiMap; 16 | import com.google.common.collect.ImmutableList; 17 | import com.google.common.collect.ImmutableListMultimap; 18 | import com.google.common.collect.ImmutableMap; 19 | import com.google.common.collect.ImmutableMultimap; 20 | import com.google.common.collect.ImmutableMultiset; 21 | import com.google.common.collect.ImmutableSet; 22 | import com.google.common.collect.ImmutableSetMultimap; 23 | import com.google.common.collect.ImmutableSortedMap; 24 | import com.google.common.collect.ImmutableSortedSet; 25 | import com.google.common.collect.LinkedHashMultimap; 26 | import com.google.common.collect.LinkedHashMultiset; 27 | import com.google.common.collect.LinkedListMultimap; 28 | import com.google.common.collect.MapMaker; 29 | import com.google.common.collect.Maps; 30 | import com.google.common.collect.Multimap; 31 | import com.google.common.collect.Multiset; 32 | import com.google.common.collect.Table; 33 | import com.google.common.collect.TreeBasedTable; 34 | import com.google.common.collect.TreeMultimap; 35 | import com.google.common.collect.TreeMultiset; 36 | import java.lang.reflect.Constructor; 37 | import java.util.ArrayDeque; 38 | import java.util.ArrayList; 39 | import java.util.Collection; 40 | import java.util.HashMap; 41 | import java.util.HashSet; 42 | import java.util.LinkedHashMap; 43 | import java.util.LinkedHashSet; 44 | import java.util.LinkedList; 45 | import java.util.Map; 46 | import java.util.PriorityQueue; 47 | import java.util.TreeMap; 48 | import java.util.TreeSet; 49 | import java.util.WeakHashMap; 50 | import java.util.concurrent.ConcurrentHashMap; 51 | import java.util.concurrent.ConcurrentSkipListSet; 52 | import java.util.concurrent.CopyOnWriteArrayList; 53 | import java.util.concurrent.CopyOnWriteArraySet; 54 | import java.util.concurrent.DelayQueue; 55 | import java.util.concurrent.Delayed; 56 | import java.util.concurrent.LinkedBlockingDeque; 57 | import java.util.concurrent.LinkedBlockingQueue; 58 | import java.util.concurrent.PriorityBlockingQueue; 59 | import java.util.concurrent.Semaphore; 60 | import java.util.concurrent.TimeUnit; 61 | import java.util.concurrent.locks.ReentrantLock; 62 | import java.util.concurrent.locks.ReentrantReadWriteLock; 63 | import objectexplorer.MemoryMeasurer; 64 | import objectexplorer.ObjectGraphMeasurer; 65 | import objectexplorer.ObjectGraphMeasurer.Footprint; 66 | 67 | public class ElementCostOfDataStructures { 68 | public static void main(String[] args) throws Exception { 69 | caption(String.format(" %2s-bit architecture ", System.getProperty("sun.arch.data.model"))); 70 | caption(" Basic Lists, Sets, Maps "); 71 | 72 | analyze(new CollectionPopulator(defaultSupplierFor(ArrayList.class))); 73 | analyze(new ImmutableListPopulator()); 74 | 75 | analyze(new CollectionPopulator(defaultSupplierFor(HashSet.class))); 76 | analyze(new ImmutableSetPopulator()); 77 | 78 | analyze(new CollectionPopulator(defaultSupplierFor(TreeSet.class), EntryFactories.COMPARABLE)); 79 | analyze(new ImmutableSortedSetPopulator()); 80 | 81 | analyze(new MapPopulator(defaultSupplierFor(HashMap.class))); 82 | analyze(new ImmutableMapPopulator()); 83 | analyze(new MapPopulator(defaultSupplierFor(LinkedHashMap.class))); 84 | 85 | analyze(new MapPopulator(defaultSupplierFor(TreeMap.class), EntryFactories.COMPARABLE)); 86 | analyze(new ImmutableSortedMapPopulator()); 87 | 88 | caption("ConcurrentHashMap/MapMaker"); 89 | 90 | analyze(new MapPopulator(defaultSupplierFor(ConcurrentHashMap.class))); 91 | analyzeMapMaker("MapMaker", new Supplier() { public MapMaker get() { return 92 | new MapMaker(); } }); 93 | analyze("MapMaker_Expires", new MapPopulator(new Supplier() { public Map get() { return 94 | new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } })); 95 | analyze("MapMaker_Evicts", new MapPopulator(new Supplier() { public Map get() { return 96 | new MapMaker().maximumSize(1000000).makeMap(); } })); 97 | analyze("MapMaker_Expires_Evicts", new MapPopulator(new Supplier() { public Map get() { return 98 | new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).makeMap(); } })); 99 | analyze("MapMaker_SoftKeys", new MapPopulator(new Supplier() { public Map get() { return 100 | new MapMaker().softKeys().makeMap(); } })); 101 | analyze("MapMaker_SoftValues", new MapPopulator(new Supplier() { public Map get() { return 102 | new MapMaker().softValues().makeMap(); } })); 103 | analyze("MapMaker_SoftKeysValues", new MapPopulator(new Supplier() { public Map get() { return 104 | new MapMaker().softKeys().softValues().makeMap(); } })); 105 | analyze("MapMaker_Evicts_SoftKeys", new MapPopulator(new Supplier() { public Map get() { return 106 | new MapMaker().maximumSize(1000000).softKeys().makeMap(); } })); 107 | analyze("MapMaker_Evicts_SoftValues", new MapPopulator(new Supplier() { public Map get() { return 108 | new MapMaker().maximumSize(1000000).softValues().makeMap(); } })); 109 | analyze("MapMaker_Evicts_SoftKeysValues", new MapPopulator(new Supplier() { public Map get() { return 110 | new MapMaker().maximumSize(1000000).softKeys().softValues().makeMap(); } })); 111 | analyze("MapMaker_Expires_SoftKeys", new MapPopulator(new Supplier() { public Map get() { return 112 | new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } })); 113 | analyze("MapMaker_Expires_SoftValues", new MapPopulator(new Supplier() { public Map get() { return 114 | new MapMaker().expiration(3, TimeUnit.DAYS).softValues().makeMap(); } })); 115 | analyze("MapMaker_Expires_SoftKeysValues", new MapPopulator(new Supplier() { public Map get() { return 116 | new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } })); 117 | analyze("MapMaker_Expires_Evicts_SoftKeys", new MapPopulator(new Supplier() { public Map get() { return 118 | new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } })); 119 | analyze("MapMaker_Expires_Evicts_SoftValues", new MapPopulator(new Supplier() { public Map get() { return 120 | new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softValues().makeMap(); } })); 121 | analyze("MapMaker_Expires_Evicts_SoftKeysValues", new MapPopulator(new Supplier() { public Map get() { return 122 | new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } })); 123 | 124 | caption(" Multisets "); 125 | 126 | analyze("HashMultiset_Worst", new MultisetPopulator_Worst(new Supplier() { public Multiset get() { return 127 | HashMultiset.create(); } })); 128 | analyze("LinkedHashMultiset_Worst", new MultisetPopulator_Worst(new Supplier() { public Multiset get() { return 129 | LinkedHashMultiset.create(); } })); 130 | analyze("TreeMultiset_Worst", new MultisetPopulator_Worst(new Supplier() { public Multiset get() { return 131 | TreeMultiset.create(); } }, EntryFactories.COMPARABLE)); 132 | analyze("ConcurrentHashMultiset_Worst", new MultisetPopulator_Worst(new Supplier() { public Multiset get() { return 133 | ConcurrentHashMultiset.create(); } })); 134 | 135 | System.out.println(); 136 | 137 | analyze("HashMultiset_Best ", new MultisetPopulator_Best(new Supplier() { public Multiset get() { return 138 | HashMultiset.create(); } })); 139 | analyze("LinkedHashMultiset_Best ", new MultisetPopulator_Best(new Supplier() { public Multiset get() { return 140 | LinkedHashMultiset.create(); } })); 141 | analyze("TreeMultiset_Best ", new MultisetPopulator_Best(new Supplier() { public Multiset get() { return 142 | TreeMultiset.create(); } }, EntryFactories.COMPARABLE)); 143 | analyze("ConcurrentHashMultiset_Best ", new MultisetPopulator_Best(new Supplier() { public Multiset get() { return 144 | ConcurrentHashMultiset.create(); } })); 145 | 146 | caption(" Multimaps "); 147 | 148 | analyze("HashMultimap_Worst", new MultimapPopulator_Worst(new Supplier() { public Multimap get() { return 149 | HashMultimap.create(); } })); 150 | analyze("LinkedHashMultimap_Worst", new MultimapPopulator_Worst(new Supplier() { public Multimap get() { return 151 | LinkedHashMultimap.create(); } })); 152 | analyze("TreeMultimap_Worst", new MultimapPopulator_Worst(new Supplier() { public Multimap get() { return 153 | TreeMultimap.create(); } }, EntryFactories.COMPARABLE)); 154 | analyze("ArrayListMultimap_Worst", new MultimapPopulator_Worst(new Supplier() { public Multimap get() { return 155 | ArrayListMultimap.create(); } })); 156 | analyze("LinkedListMultimap_Worst", new MultimapPopulator_Worst(new Supplier() { public Multimap get() { return 157 | LinkedListMultimap.create(); } })); 158 | analyze(new ImmutableMultimapPopulator_Worst()); 159 | analyze(new ImmutableListMultimapPopulator_Worst()); 160 | analyze(new ImmutableSetMultimapPopulator_Worst()); 161 | 162 | System.out.println(); 163 | 164 | analyze("HashMultimap_Best ", new MultimapPopulator_Best(new Supplier() { public Multimap get() { return 165 | HashMultimap.create(); } })); 166 | analyze("LinkedHashMultimap_Best ", new MultimapPopulator_Best(new Supplier() { public Multimap get() { return 167 | LinkedHashMultimap.create(); } })); 168 | analyze("TreeMultimap_Best ", new MultimapPopulator_Best(new Supplier() { public Multimap get() { return 169 | TreeMultimap.create(); } }, EntryFactories.COMPARABLE)); 170 | analyze("ArrayListMultimap_Best ", new MultimapPopulator_Best(new Supplier() { public Multimap get() { return 171 | ArrayListMultimap.create(); } })); 172 | analyze("LinkedListMultimap_Best ", new MultimapPopulator_Best(new Supplier() { public Multimap get() { return 173 | LinkedListMultimap.create(); } })); 174 | analyze(new ImmutableMultimapPopulator_Best()); 175 | analyze(new ImmutableListMultimapPopulator_Best()); 176 | analyze(new ImmutableSetMultimapPopulator_Best()); 177 | 178 | caption(" Tables "); 179 | 180 | analyze("HashBasedTable", new TablePopulator_Worst(new Supplier() { public Table get() { return 181 | HashBasedTable.create(); } } )); 182 | analyze("TreeBasedTable", new TablePopulator_Worst(new Supplier
() { public Table get() { return 183 | TreeBasedTable.create(); } }, EntryFactories.COMPARABLE)); 184 | 185 | caption(" BiMaps "); 186 | 187 | analyze("HashBiMap", new MapPopulator(new Supplier() { public Map get() { return 188 | HashBiMap.create(); } })); 189 | analyze(new ImmutableBiMapPopulator()); 190 | 191 | caption(" Misc "); 192 | 193 | analyze(new MapPopulator(defaultSupplierFor(WeakHashMap.class))); 194 | analyze(new CollectionPopulator(defaultSupplierFor(LinkedList.class))); 195 | analyze(new CollectionPopulator(defaultSupplierFor(ArrayDeque.class))); 196 | analyze(new CollectionPopulator(defaultSupplierFor(LinkedHashSet.class))); 197 | analyze(new CollectionPopulator(defaultSupplierFor(PriorityQueue.class), EntryFactories.COMPARABLE)); 198 | analyze(new CollectionPopulator(defaultSupplierFor(PriorityBlockingQueue.class), EntryFactories.COMPARABLE)); 199 | analyze(new CollectionPopulator(defaultSupplierFor(ConcurrentSkipListSet.class), EntryFactories.COMPARABLE)); 200 | analyze(new CollectionPopulator(defaultSupplierFor(CopyOnWriteArrayList.class))); 201 | analyze(new CollectionPopulator(defaultSupplierFor(CopyOnWriteArraySet.class))); 202 | analyze(new CollectionPopulator(defaultSupplierFor(DelayQueue.class), EntryFactories.DELAYED)); 203 | analyze(new CollectionPopulator(defaultSupplierFor(LinkedBlockingQueue.class))); 204 | analyze(new CollectionPopulator(defaultSupplierFor(LinkedBlockingDeque.class))); 205 | 206 | caption(" Synchronization Structures"); 207 | 208 | analyzeOneOff("ReentrantLock", new ReentrantLock(true)); 209 | analyzeOneOff("Semaphore", new Semaphore(1, true)); 210 | analyzeOneOff("ReadWriteLock", new ReentrantReadWriteLock(true)); 211 | } 212 | 213 | private static void caption(String caption) { 214 | System.out.println(); 215 | System.out.println("========================================== " + caption 216 | + " =========================================="); 217 | System.out.println(); 218 | } 219 | 220 | private static void analyzeMapMaker(String caption, Supplier supplier) { 221 | analyze(caption, new MapPopulator(new MapSupplier(supplier))); 222 | analyze(caption + "_Computing", new MapPopulator(new ComputingMapSupplier(supplier))); 223 | } 224 | 225 | private static class MapSupplier implements Supplier { 226 | private final Supplier mapMakerSupplier; 227 | MapSupplier(Supplier mapMakerSupplier) { 228 | this.mapMakerSupplier = mapMakerSupplier; 229 | } 230 | 231 | public Map get() { 232 | return mapMakerSupplier.get().makeMap(); 233 | } 234 | } 235 | 236 | private static class ComputingMapSupplier implements Supplier { 237 | private final Supplier mapMakerSupplier; 238 | ComputingMapSupplier(Supplier mapMakerSupplier) { 239 | this.mapMakerSupplier = mapMakerSupplier; 240 | } 241 | 242 | public Map get() { 243 | return mapMakerSupplier.get().makeComputingMap(new Function() { 244 | public Object apply(Object o) { 245 | return o; 246 | } 247 | }); 248 | } 249 | } 250 | 251 | static void analyze(Populator populator) { 252 | analyze(populator.toString(), populator); 253 | } 254 | 255 | static void analyze(String caption, Populator populator) { 256 | AvgEntryCost cost = averageEntryCost(populator, 16, 256 * 31); 257 | System.out.printf("%40s :: Bytes = %6.2f, Objects = %5.2f Refs = %5.2f Primitives = %s%n", 258 | caption, cost.bytes, cost.objects, cost.refs, cost.primitives); 259 | } 260 | 261 | static void analyzeOneOff(String caption, Object o) { 262 | Footprint footprint = ObjectGraphMeasurer.measure(o); 263 | long bytes = MemoryMeasurer.measureBytes(o); 264 | System.out.printf("%40s :: Bytes = %6d, Objects = %5d Refs = %5d Primitives = %s%n", 265 | caption, bytes, footprint.getObjects(), footprint.getReferences(), footprint.getPrimitives()); 266 | } 267 | 268 | static AvgEntryCost averageEntryCost(Populator populator, int initialEntries, int entriesToAdd) { 269 | Preconditions.checkArgument(initialEntries >= 0, "initialEntries negative"); 270 | Preconditions.checkArgument(entriesToAdd > 0, "entriesToAdd negative or zero"); 271 | 272 | Predicate predicate = Predicates.not(Predicates.instanceOf( 273 | populator.getEntryType())); 274 | 275 | Object collection1 = populator.construct(initialEntries); 276 | Footprint footprint1 = ObjectGraphMeasurer.measure(collection1, predicate); 277 | long bytes1 = MemoryMeasurer.measureBytes(collection1, predicate); 278 | 279 | Object collection2 = populator.construct(initialEntries + entriesToAdd); 280 | Footprint footprint2 = ObjectGraphMeasurer.measure(collection2, predicate); 281 | long bytes2 = MemoryMeasurer.measureBytes(collection2, predicate); 282 | 283 | double objects = (footprint2.getObjects() - footprint1.getObjects()) / (double) entriesToAdd; 284 | double refs = (footprint2.getReferences() - footprint1.getReferences()) / (double) entriesToAdd; 285 | double bytes = (bytes2 - bytes1) / (double)entriesToAdd; 286 | 287 | Map, Double> primitives = Maps.newHashMap(); 288 | for (Class primitiveType : primitiveTypes) { 289 | int initial = footprint1.getPrimitives().count(primitiveType); 290 | int ending = footprint2.getPrimitives().count(primitiveType); 291 | if (initial != ending) { 292 | primitives.put(primitiveType, (ending - initial) / (double) entriesToAdd); 293 | } 294 | } 295 | 296 | return new AvgEntryCost(objects, refs, primitives, bytes); 297 | } 298 | 299 | private static final ImmutableSet> primitiveTypes = ImmutableSet.>of( 300 | boolean.class, byte.class, char.class, short.class, 301 | int.class, float.class, long.class, double.class); 302 | 303 | private static class AvgEntryCost { 304 | final double objects; 305 | final double refs; 306 | final ImmutableMap, Double> primitives; 307 | final double bytes; 308 | AvgEntryCost(double objects, double refs, Map, Double> primitives, double bytes) { 309 | this.objects = objects; 310 | this.refs = refs; 311 | this.primitives = ImmutableMap.copyOf(primitives); 312 | this.bytes = bytes; 313 | } 314 | } 315 | 316 | private static class DefaultConstructorSupplier implements Supplier { 317 | private final Constructor constructor; 318 | DefaultConstructorSupplier(Class clazz) throws NoSuchMethodException { 319 | this.constructor = clazz.getConstructor(); 320 | } 321 | public C get() { 322 | try { 323 | return constructor.newInstance(); 324 | } catch (Exception e) { 325 | throw Throwables.propagate(e); 326 | } 327 | } 328 | 329 | @Override 330 | public String toString() { 331 | return constructor.getDeclaringClass().getSimpleName(); 332 | } 333 | } 334 | 335 | static DefaultConstructorSupplier defaultSupplierFor(Class clazz) throws NoSuchMethodException { 336 | return new DefaultConstructorSupplier(clazz); 337 | } 338 | } 339 | 340 | interface Populator { 341 | Class getEntryType(); 342 | 343 | C construct(int entries); 344 | } 345 | 346 | abstract class AbstractPopulator implements Populator { 347 | private final EntryFactory entryFactory; 348 | AbstractPopulator() { this(EntryFactories.REGULAR); } 349 | AbstractPopulator(EntryFactory entryFactory) { 350 | this.entryFactory = entryFactory; 351 | } 352 | 353 | protected Object newEntry() { 354 | return entryFactory.get(); 355 | } 356 | 357 | public Class getEntryType() { 358 | return entryFactory.getEntryType(); 359 | } 360 | } 361 | 362 | abstract class MutablePopulator extends AbstractPopulator { 363 | private final Supplier factory; 364 | 365 | MutablePopulator(Supplier factory) { 366 | this(factory, EntryFactories.REGULAR); 367 | } 368 | 369 | MutablePopulator(Supplier factory, EntryFactory entryFactory) { 370 | super(entryFactory); 371 | this.factory = factory; 372 | } 373 | 374 | protected abstract void addEntry(C target); 375 | 376 | public C construct(int entries) { 377 | C collection = factory.get(); 378 | for (int i = 0; i < entries; i++) { 379 | addEntry(collection); 380 | } 381 | return collection; 382 | } 383 | 384 | @Override 385 | public String toString() { 386 | return factory.toString(); 387 | } 388 | } 389 | 390 | class MapPopulator extends MutablePopulator { 391 | MapPopulator(Supplier mapFactory) { 392 | super(mapFactory); 393 | } 394 | 395 | MapPopulator(Supplier mapFactory, EntryFactory entryFactory) { 396 | super(mapFactory, entryFactory); 397 | } 398 | 399 | public void addEntry(Map map) { 400 | map.put(newEntry(), newEntry()); 401 | } 402 | } 403 | 404 | class CollectionPopulator extends MutablePopulator { 405 | CollectionPopulator(Supplier collectionFactory) { 406 | super(collectionFactory); 407 | } 408 | 409 | CollectionPopulator(Supplier collectionFactory, EntryFactory entryFactory) { 410 | super(collectionFactory, entryFactory); 411 | } 412 | 413 | public void addEntry(Collection collection) { 414 | collection.add(newEntry()); 415 | } 416 | } 417 | 418 | class MultimapPopulator_Worst extends MutablePopulator { 419 | MultimapPopulator_Worst(Supplier multimapFactory) { 420 | super(multimapFactory); 421 | } 422 | MultimapPopulator_Worst(Supplier multimapFactory, EntryFactory entryFactory) { 423 | super(multimapFactory, entryFactory); 424 | } 425 | 426 | public void addEntry(Multimap multimap) { 427 | multimap.put(newEntry(), newEntry()); 428 | } 429 | } 430 | 431 | class MultimapPopulator_Best extends MutablePopulator { 432 | MultimapPopulator_Best(Supplier multimapFactory) { 433 | super(multimapFactory); 434 | } 435 | MultimapPopulator_Best(Supplier multimapFactory, EntryFactory entryFactory) { 436 | super(multimapFactory, entryFactory); 437 | } 438 | 439 | private final Object key = newEntry(); 440 | public void addEntry(Multimap multimap) { 441 | multimap.put(key, newEntry()); 442 | } 443 | } 444 | 445 | class MultisetPopulator_Worst extends MutablePopulator { 446 | MultisetPopulator_Worst(Supplier multisetFactory) { 447 | super(multisetFactory); 448 | } 449 | MultisetPopulator_Worst(Supplier multisetFactory, EntryFactory entryFactory) { 450 | super(multisetFactory, entryFactory); 451 | } 452 | 453 | public void addEntry(Multiset multiset) { 454 | multiset.add(newEntry()); 455 | } 456 | } 457 | 458 | class MultisetPopulator_Best extends MutablePopulator { 459 | MultisetPopulator_Best(Supplier multisetFactory) { 460 | super(multisetFactory); 461 | } 462 | MultisetPopulator_Best(Supplier multisetFactory, EntryFactory entryFactory) { 463 | super(multisetFactory, entryFactory); 464 | } 465 | 466 | private final Object key = newEntry(); 467 | public void addEntry(Multiset multiset) { 468 | multiset.add(key); 469 | } 470 | } 471 | 472 | class TablePopulator_Worst extends MutablePopulator
{ 473 | TablePopulator_Worst(Supplier tableFactory) { 474 | super(tableFactory); 475 | } 476 | TablePopulator_Worst(Supplier tableFactory, EntryFactory entryFactory) { 477 | super(tableFactory, entryFactory); 478 | } 479 | 480 | public void addEntry(Table table) { 481 | table.put(newEntry(), newEntry(), newEntry()); 482 | } 483 | } 484 | 485 | /** Immutable classes */ 486 | 487 | class ImmutableListPopulator extends AbstractPopulator { 488 | public ImmutableList construct(int entries) { 489 | ImmutableList.Builder builder = ImmutableList.builder(); 490 | for (int i = 0; i < entries; i++) { 491 | builder.add(newEntry()); 492 | } 493 | return builder.build(); 494 | } 495 | 496 | @Override 497 | public String toString() { 498 | return "ImmutableList"; 499 | } 500 | } 501 | 502 | class ImmutableSetPopulator extends AbstractPopulator { 503 | public ImmutableSet construct(int entries) { 504 | ImmutableSet.Builder builder = ImmutableSet.builder(); 505 | for (int i = 0; i < entries; i++) { 506 | builder.add(newEntry()); 507 | } 508 | return builder.build(); 509 | } 510 | 511 | @Override 512 | public String toString() { 513 | return "ImmutableSet"; 514 | } 515 | } 516 | 517 | class ImmutableMapPopulator extends AbstractPopulator { 518 | public ImmutableMap construct(int entries) { 519 | ImmutableMap.Builder builder = ImmutableMap.builder(); 520 | for (int i = 0; i < entries; i++) { 521 | builder.put(newEntry(), newEntry()); 522 | } 523 | return builder.build(); 524 | } 525 | 526 | @Override 527 | public String toString() { 528 | return "ImmutableMap"; 529 | } 530 | } 531 | 532 | class ImmutableSortedSetPopulator extends AbstractPopulator { 533 | ImmutableSortedSetPopulator() { 534 | super(EntryFactories.COMPARABLE); 535 | } 536 | 537 | public ImmutableSortedSet construct(int entries) { 538 | ImmutableSortedSet.Builder builder = ImmutableSortedSet.naturalOrder(); 539 | for (int i = 0; i < entries; i++) { 540 | builder.add(newEntry()); 541 | } 542 | return builder.build(); 543 | } 544 | 545 | @Override 546 | public String toString() { 547 | return "ImmutableSortedSet"; 548 | } 549 | } 550 | 551 | class ImmutableSortedMapPopulator extends AbstractPopulator { 552 | ImmutableSortedMapPopulator() { 553 | super(EntryFactories.COMPARABLE); 554 | } 555 | 556 | public ImmutableSortedMap construct(int entries) { 557 | ImmutableSortedMap.Builder builder = ImmutableSortedMap.naturalOrder(); 558 | for (int i = 0; i < entries; i++) { 559 | builder.put(newEntry(), newEntry()); 560 | } 561 | return builder.build(); 562 | } 563 | 564 | @Override 565 | public String toString() { 566 | return "ImmutableSortedMap"; 567 | } 568 | } 569 | 570 | class ImmutableBiMapPopulator extends AbstractPopulator { 571 | public ImmutableBiMap construct(int entries) { 572 | ImmutableBiMap.Builder builder = ImmutableBiMap.builder(); 573 | for (int i = 0; i < entries; i++) { 574 | builder.put(newEntry(), newEntry()); 575 | } 576 | return builder.build(); 577 | } 578 | 579 | @Override 580 | public String toString() { 581 | return "ImmutableBiMap"; 582 | } 583 | } 584 | 585 | class ImmutableMultimapPopulator_Worst extends AbstractPopulator { 586 | public ImmutableMultimap construct(int entries) { 587 | ImmutableMultimap.Builder builder = ImmutableMultimap.builder(); 588 | for (int i = 0; i < entries; i++) { 589 | builder.put(newEntry(), newEntry()); 590 | } 591 | return builder.build(); 592 | } 593 | 594 | @Override 595 | public String toString() { 596 | return "ImmutableMultimap_Worst"; 597 | } 598 | } 599 | 600 | class ImmutableMultimapPopulator_Best extends AbstractPopulator { 601 | public ImmutableMultimap construct(int entries) { 602 | ImmutableMultimap.Builder builder = ImmutableMultimap.builder(); 603 | Object key = newEntry(); 604 | for (int i = 0; i < entries; i++) { 605 | builder.put(key, newEntry()); 606 | } 607 | return builder.build(); 608 | } 609 | 610 | @Override 611 | public String toString() { 612 | return "ImmutableMultimap_Best "; 613 | } 614 | } 615 | 616 | class ImmutableListMultimapPopulator_Worst extends AbstractPopulator { 617 | public ImmutableListMultimap construct(int entries) { 618 | ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); 619 | for (int i = 0; i < entries; i++) { 620 | builder.put(newEntry(), newEntry()); 621 | } 622 | return builder.build(); 623 | } 624 | 625 | @Override 626 | public String toString() { 627 | return "ImmutableListMultimap_Worst"; 628 | } 629 | } 630 | 631 | class ImmutableListMultimapPopulator_Best extends AbstractPopulator { 632 | public ImmutableListMultimap construct(int entries) { 633 | ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); 634 | Object key = newEntry(); 635 | for (int i = 0; i < entries; i++) { 636 | builder.put(key, newEntry()); 637 | } 638 | return builder.build(); 639 | } 640 | 641 | @Override 642 | public String toString() { 643 | return "ImmutableListMultimap_Best "; 644 | } 645 | } 646 | 647 | class ImmutableSetMultimapPopulator_Worst extends AbstractPopulator { 648 | public ImmutableSetMultimap construct(int entries) { 649 | ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); 650 | for (int i = 0; i < entries; i++) { 651 | builder.put(newEntry(), newEntry()); 652 | } 653 | return builder.build(); 654 | } 655 | 656 | @Override 657 | public String toString() { 658 | return "ImmutableSetMultimap_Worst"; 659 | } 660 | } 661 | 662 | class ImmutableSetMultimapPopulator_Best extends AbstractPopulator { 663 | public ImmutableSetMultimap construct(int entries) { 664 | ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); 665 | Object key = newEntry(); 666 | for (int i = 0; i < entries; i++) { 667 | builder.put(key, newEntry()); 668 | } 669 | return builder.build(); 670 | } 671 | 672 | @Override 673 | public String toString() { 674 | return "ImmutableSetMultimap_Best "; 675 | } 676 | } 677 | 678 | class ImmutableMultisetPopulator_Worst extends AbstractPopulator { 679 | public ImmutableMultiset construct(int entries) { 680 | ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); 681 | for (int i = 0; i < entries; i++) { 682 | builder.add(newEntry()); 683 | } 684 | return builder.build(); 685 | } 686 | 687 | @Override 688 | public String toString() { 689 | return "ImmutableMultiset_Worst"; 690 | } 691 | } 692 | 693 | class ImmutableMultisetPopulator_Best extends AbstractPopulator { 694 | public ImmutableMultiset construct(int entries) { 695 | ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); 696 | Object key = newEntry(); 697 | for (int i = 0; i < entries; i++) { 698 | builder.add(key); 699 | } 700 | return builder.build(); 701 | } 702 | 703 | @Override 704 | public String toString() { 705 | return "ImmutableMultiset_Best "; 706 | } 707 | } 708 | 709 | interface EntryFactory extends Supplier { 710 | Class getEntryType(); 711 | } 712 | 713 | enum EntryFactories implements EntryFactory { 714 | REGULAR { 715 | public Class getEntryType() { return Element.class; } 716 | public Object get() { return new Element(); } 717 | }, 718 | COMPARABLE { 719 | public Class getEntryType() { return ComparableElement.class; } 720 | public Object get() { return new ComparableElement(); } 721 | }, 722 | DELAYED { 723 | public Class getEntryType() { return DelayedElement.class; } 724 | public Object get() { return new DelayedElement(); } 725 | }; 726 | } 727 | 728 | class Element { } 729 | 730 | class ComparableElement extends Element implements Comparable { 731 | public int compareTo(Object o) { if (this == o) return 0; else return 1; } 732 | } 733 | 734 | class DelayedElement extends Element implements Delayed { 735 | public long getDelay(TimeUnit unit) { return 0; } 736 | public int compareTo(Delayed o) { if (this == o) return 0; else return 1; } 737 | } 738 | -------------------------------------------------------------------------------- /src/test/java/objectexplorer/ObjectSerializerTest.java: -------------------------------------------------------------------------------- 1 | package objectexplorer; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Arrays; 6 | import java.util.HashMap; 7 | import java.util.HashSet; 8 | import java.util.LinkedHashSet; 9 | 10 | import org.junit.Test; 11 | 12 | public class ObjectSerializerTest { 13 | 14 | @Test 15 | public void simpleTest() { 16 | // HashMap rootObject1 = new HashMap(); 17 | // rootObject1.put(2, 2); 18 | // rootObject1.put(3, 3); 19 | // rootObject1.put(4, 4); 20 | // rootObject1.put(1, 1); 21 | // rootObject1.put("new dog", "new dog"); 22 | // 23 | // HashMap rootObject2 = new HashMap(); 24 | // rootObject2.put(1, 1); 25 | // rootObject2.put(4, 4); 26 | // rootObject2.put("new dog", "new dog"); 27 | // rootObject2.put(2, 2); 28 | // rootObject2.put(3, 3); 29 | 30 | // Object rootObject1 = new LinkedHashSet(Arrays.asList(2, 3, 4, 1, "new dog")); 31 | // Object rootObject2 = new LinkedHashSet(Arrays.asList(1, 4, "new dog", 2, 3)); 32 | 33 | // Object rootObject1 = new HashSet(Arrays.asList(2, 3, 4, 1, "new dog")); 34 | // Object rootObject2 = new HashSet(Arrays.asList(1, 4, "new dog", 2, 3)); 35 | 36 | // Object rootObject1 = new HashSet(Arrays.asList(2, 3, 4, 1, "new dog", 17)); 37 | // Object rootObject2 = new HashSet(Arrays.asList(17, 1, 4, "new dog", 2, 3)); 38 | 39 | HashSet rootObject1 = new HashSet(Arrays.asList(2, 3, 4, 1, "new dog", 17)); 40 | HashSet rootObject2 = new HashSet(Arrays.asList(2, 3, 4, 1, "new dog")); 41 | rootObject2.add(17); 42 | rootObject2.add(15); 43 | rootObject2.remove(15); 44 | 45 | assertEquals(rootObject2, rootObject2); 46 | 47 | System.out.println(ObjectGraphMeasurer.measure(rootObject1)); 48 | System.out.println(ObjectGraphMeasurer.measure(rootObject2)); 49 | 50 | System.out.print("\n\n\n"); 51 | 52 | System.out.println(ObjectSerializer.measure(rootObject1)); 53 | System.out.print("\n\n\n"); 54 | System.out.println(ObjectSerializer.measure(rootObject2)); 55 | } 56 | 57 | } 58 | --------------------------------------------------------------------------------