Re: copy on write implementation of Strings
Thomas Pornin wrote:
According to Roedy Green <see_website@mindprod.com.invalid>:
It seems to me substring once worked that way but now copies in order
to avoid pinning a large unused string in RAM.
From what I see in JDK-1.6.0 source, they still work that way.
It is easy to show that it is the case.
Example (based on some code posted here recently by someone else for
another purpose):
import java.lang.reflect.*;
public class Ups {
public static void setchar(String str, int ix, char ch) throws
Exception {
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
Array.setChar(field.get(str), ix, ch);
}
public static void main(final String[] args) throws Throwable {
String str = "alpha";
String str2 = str.substring(0, 3);
System.out.println(str);
System.out.println(str2);
setchar(str, 1, 'x');
System.out.println(str );
System.out.println(str2);
}
}
Arne