I have limited heap memory in JVM and I cannot increase it as it a embedded device. How ever I would like to execute few logging scripts after out of memory error occurs. how do I do that?
Asked
Active
Viewed 1,722 times
2
-
2You can't, you're out of memory. – Elliott Frisch Jun 22 '16 at 10:03
-
@ElliottFrisch ..Thanks for quick response. but out of memory is in JVM right? can't I detect it before hand? Is there any technique? There must be some thing we can do. – rocktopus Jun 22 '16 at 10:07
-
Probably duplicates with http://stackoverflow.com/questions/12096403/java-shutting-down-on-out-of-memory-error – waltersu Jun 22 '16 at 10:27
2 Answers
3
There is an java option flag you can set when starting the JVM, that will execute a given script whhen an OOM occurs.
-XX:OnOutOfMemoryError=string
is used to specify a command or script to execute when an OutOfMemoryError is first thrown

DXTR66
- 563
- 5
- 17
0
Here is a little code which from you can get the data you will need.
Actually is nearly impossible catching when you JVM will go on "Out Of Memory".
The only way for doing this should be check if "Free Memory" is getting 0 at runtime, but doing this could be very heavy and so you will reach "Out Of Memory" easly.
int mb = 1024*1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
//Print used memory
System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);
//Print free memory
System.out.println("Free Memory:" + runtime.freeMemory() / mb);
//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / mb);
//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / mb);

RudiDudi
- 455
- 1
- 7
- 18
-
Thanks. But as you rightly said its very heavy so I can't use it. But please do reply if you find anything else. – rocktopus Jun 22 '16 at 10:29