- 一个线程安全,一个不安全
- 不断调用toString方法,buffer不回重复new一个对象,但是builder会。
@Test
public void testBuffer() throws Exception {
StringBuffer buffer = new StringBuffer("aaa");
String s1 = buffer.toString();
String s2 = buffer.toString();
String s3 = buffer.toString();
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
char[] o1 = (char[]) value.get(s1);
char[] o2 = (char[]) value.get(s2);
char[] o3 = (char[]) value.get(s3);
System.out.println((Object) o1);
System.out.println((Object) o2);
System.out.println((Object) o3);
}
// [C@6996db8
// [C@6996db8
// [C@6996db8
@Test
public void testBuilder() throws Exception {
StringBuilder buffer = new StringBuilder("aaa");
String s1 = buffer.toString();
String s2 = buffer.toString();
String s3 = buffer.toString();
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
char[] o1 = (char[]) value.get(s1);
char[] o2 = (char[]) value.get(s2);
char[] o3 = (char[]) value.get(s3);
System.out.println((Object) o1);
System.out.println((Object) o2);
System.out.println((Object) o3);
}
// [C@6996db8
// [C@1963006a
// [C@7fbe847c