Created
May 20, 2014 17:10
-
-
Save gaul/6a6d958a0c120ec98e74 to your computer and use it in GitHub Desktop.
Demonstrate overhead of primitives stored in an object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Demonstrate overhead of primitives stored in an object. Note that each | |
* object has 12 bytes of overhead for the class pointer, flags, and monitor and | |
* the JVM pads each object to the next 8 byte alignment. Thus an object with | |
* two byte fields will consume 16 bytes and an object with two int fields will | |
* consume 24 bytes: | |
* | |
* $ javac PrimitiveOverhead.java ; java PrimitiveOverhead | |
* | |
* num #instances #bytes class name | |
* ---------------------------------------------- | |
* 1: 16777216 402653184 PrimitiveOverhead$IntClass | |
* 2: 16777216 268435456 PrimitiveOverhead$ByteClass | |
* 3: 315 134230920 [Ljava.lang.Object; | |
*/ | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.io.IOException; | |
public class PrimitiveOverhead { | |
static final class ByteClass { byte x, y; } | |
static final class IntClass { int x, y; } | |
private static int LENGTH = 16 * 1024 * 1024; | |
private static final Object[] byteArray = new Object[LENGTH]; | |
private static final Object[] intArray = new Object[LENGTH]; | |
public static void main(String[] args) throws Exception { | |
for (int i = 0; i < LENGTH; ++i) { | |
byteArray[i] = new ByteClass(); | |
intArray[i] = new IntClass(); | |
} | |
System.out.print(runCommand(new String[] { | |
"sh", "-c", "jmap -histo:live $PPID | head -6"})); | |
} | |
private static String runCommand(final String[] args) throws IOException { | |
StringBuilder builder = new StringBuilder(); | |
Process child = Runtime.getRuntime().exec(args); | |
try (BufferedReader reader = new BufferedReader(new InputStreamReader( | |
child.getInputStream()))) { | |
String line; | |
while ((line = reader.readLine()) != null) { | |
builder.append(line).append('\n'); | |
} | |
} | |
return builder.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment