Created
March 24, 2012 21:34
-
-
Save cky/2188260 to your computer and use it in GitHub Desktop.
Test your JVM's string interning behaviour under string mutation!
This file contains hidden or 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
import java.lang.reflect.Field; | |
public class Evil { | |
private static final Field valueField; | |
static { | |
try { | |
valueField = String.class.getDeclaredField("value"); | |
valueField.setAccessible(true); | |
} catch (NoSuchFieldException exc) { | |
throw new AssertionError(exc); | |
} | |
} | |
private static char[] getValue(String str) { | |
try { | |
return (char[]) valueField.get(str); | |
} catch (IllegalAccessException exc) { | |
throw new AssertionError(exc); | |
} | |
} | |
private static String string(char... chars) { | |
return new String(chars); | |
} | |
private static void dump(String legend, String str) { | |
String intern = str.intern(); | |
System.out.printf("%15s: %s[%#x]; intern: %s[%#x]%n", legend, | |
str, System.identityHashCode(str), | |
intern, System.identityHashCode(intern)); | |
} | |
public static void main(String[] args) { | |
dump("'foo' initial", "foo"); | |
dump("'goo' initial", "goo"); | |
++getValue("foo")[0]; | |
dump("'foo' changed", "foo"); | |
dump("'goo' unchanged", "goo"); | |
dump("'f', 'o', 'o'", string('f', 'o', 'o')); | |
--getValue("goo")[0]; | |
dump("'foo' changed", "foo"); | |
dump("'goo' changed", "goo"); | |
dump("'g', 'o', 'o'", string('g', 'o', 'o')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment