I have a following piece of code:
List<String> list = new ArrayList<String>();
// WeakReference<List> wr = new WeakReference<List>(list);
System.out.println(" before tot memory... " + Runtime.getRuntime().totalMemory());
System.out.println(" before free memory... " + Runtime.getRuntime().freeMemory());
for(int i =0; i<100; i++)
list.add(new String("hello"));
//System.gc();
list = null; //forcefully end its life expectancy
System.out.println(" after tot memory... " + Runtime.getRuntime().totalMemory());
System.out.println(" after free memory... " + Runtime.getRuntime().freeMemory());
System.out.println(" after memory used ... " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
// System.out.println(" weak reference " + wr.get());
When I run the above code, I can see the free memory is 361064(In my system, however this value may vary)
But when I run the above code with System.gc() and comment list=null , I can see my free memory is coming(160944 in this case) less than the above test case. In both the scenarios, the objects are removed from memory.But why these values are different.
new String("hello")creates two objects. This constructor should be never use. Trylist.add("hello")