import java.util.ArrayList; import java.util.List; // http://www.jtraining.com/blogs/string-and-memory-leaks-in-java.html // http://www.javablogging.com/string-and-memory-leaks/ public class TestStringOutOfMemoryError { public static void main(String[] args) throws Exception { testWithOutOfMemoryError(); //testWithoutOutOfMemoryError(); System.out.println("HaHa!"); } public static void testWithOutOfMemoryError() { List<String> list = new ArrayList<String>(); for(int i = 0; i < 10000; i++) { list.add(getStringWithOutOfMemoryError()); } } public static void testWithoutOutOfMemoryError() { List<String> list = new ArrayList<String>(); for(int i = 0; i < 10000; i++) { list.add(getStringWithoutOutOfMemoryError()); } } public static String getStringWithOutOfMemoryError() { StringBuffer sb = new StringBuffer(); sb.append(System.currentTimeMillis()); for(int i = 0; i < 10000; i++) { sb.append("1234567890"); } String s = sb.toString(); return s.substring(0, 13); } public static String getStringWithoutOutOfMemoryError() { StringBuffer sb = new StringBuffer(); sb.append(System.currentTimeMillis()); for(int i = 0; i < 10000; i++) { sb.append("1234567890"); } String s = sb.toString(); return new String(s.substring(0, 13)); } }