2

I am working on an application written solely in Java which will often be using very large amount of data (at most 500 GB). The program will be saving data not currently in use in a database.

However, I want to keep as much data as possible within the application since a lot of it is reused often. In order to not get any out-of-memory errors I want to be able to check how much memory the application as a whole is using at any one moment, so that I can store it when the application approaches a predefined limit.

Something like this;

long memoryUsage = SomeClass.getCurrentMemoryUsage();
Anju Maaka
  • 263
  • 1
  • 10

2 Answers2

0

If you looking specifically for in JVM memory:

Runtime runtime = Runtime.getRuntime();

NumberFormat format = NumberFormat.getInstance();


StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();

sb.append("free memory: " + format.format(freeMemory / 1024) + "<br`enter code here`/>");   sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - 
allocatedMemory)) / 1024) + "<br/>");
Starmixcraft
  • 389
  • 1
  • 14
0
Runtime rt = Runtime.getRuntime(); 
long total_mem = rt.totalMemory(); 
long free_mem = rt.freeMemory(); 
long used_mem = total_mem - free_mem; 
System.out.println("Amount of used memory: " + used_mem); 

We can find the memory used at the runtime by the above code.