Skip to content

Instantly share code, notes, and snippets.

@cky
Created March 24, 2012 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cky/2188260 to your computer and use it in GitHub Desktop.
Save cky/2188260 to your computer and use it in GitHub Desktop.
Test your JVM's string interning behaviour under string mutation!
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