Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Runtime.freeMemory() - Java

Hey I'm testing out Runtime.freeMemory() with this code:

 Runtime runtime = Runtime.getRuntime();
 long freeMemory = runtime.freeMemory();

 // This is some arbitary factor that should work <= 1
 double factor = 0.8;

 int size = (int) (factor * freeMemory);
 byte[] testArray = new byte[size];

I'm creating a byte array of size close to the freeMemory value. For some reason, especially when I limit the memory of the program to around 8MB, the code throws an OutOfMemory exception for any factor > 0.55. This really doesnt make sense, surely freeMemory means freeMemory, I expect it to be a little out, but not double what actually is free.

Any suggestions on whats going on? Thanks

(Note in my tests im limiting the memory available to the program to 8MB or 16MB, using -Xmx8M etc.)

like image 770
Ricky Jones Avatar asked Aug 26 '26 23:08

Ricky Jones


1 Answers

Actually, your free memory divided to two generations: http://java.sun.com/docs/hotspot/gc1.4.2/ one is the "Young" generation, and one is the "tenured" generation. If you run with -verbose:gc -XX:+PrintGCDetails VM settings, you can see how much each generation takes. I found out that I can fill my tenured generation completely, but not more than that.

like image 99
Hila Avatar answered Aug 29 '26 14:08

Hila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!