Reputation: 181
I'm learning Java from a book called "Java 2: The Complete Reference".
The output according to the book is: Total memory is: 1048568 Initial free memory: 751392 Free memory after garbage collection: 841424 Free memory after allocation: 824000 Memory used by allocation: 17424 Free memory after collecting discarded Integers: 842640
My output is: Total memory is : 121634816 Initial free memory : 120142456 Free memory after garbage collection : 7677000 Free memory after allocation : 7635040 Memory used by allocation : 41960 Free memory after collecting discarded integers : 7677960
My problem is the above boldly mentioned part. The "initial free memory" mentioned in the output of the book is less than "free memory after garbage collection" whereas in my output "initial free memory" is way more than that of "free memory after garbage collection".
class MemoryDemo
{
public static void main(String[] args)
{
Runtime r = Runtime.getRuntime();
long mem1, mem2;
Integer someInts[] = new Integer[1000];
System.out.println("Total memory is : " + r.totalMemory());
mem1 = r.freeMemory();
System.out.println("Initial free memory : " + mem1);
r.gc();
mem1 = r.freeMemory();
System.out.println("Free memory after garbage collection : " + mem1);
for(int i = 0; i < 1000; i++)
someInts[i] = new Integer(i);
mem2 = r.freeMemory();
System.out.println("Free memory after allocation : " + mem2);
System.out.println("Memory used by allocation : " + (mem1 - mem2));
for(int i = 0; i < 1000; i++)
someInts[i] = null;
r.gc();
mem2 = r.freeMemory();
System.out.println("Free memory after collecting discarded integers :" + mem2);
}
}
I need explanation for this bit and I'm attaching a link for downloading the book in the description. The code is on 406 page of book. http://iiti.ac.in/people/~tanimad/JavaTheCompleteReference.pdf
Upvotes: 1
Views: 99
Reputation:
The memory size of a Java Virtual Machine is not a fixed quantity. You can set it at JVM startup. The default setting may vary from implementation to implementation and from version to version. The default may well depend on the size of the actual computer memory.
Upvotes: 3
Reputation: 201439
This is not an error or a mistake. Your computer has more memory than the author of the books computer had at the the time the book was written.
Upvotes: 2