I want to run several REST web applications inside one Java process to save memory and scale easily with help of Akka. I would like to estimate how much memory each request handler consume and detect these dangerous for the entire system.
-
Is it possible to monitor memory usage in almost real time inside that process and find out how much memory is used be each request handler? What I need to achieve that? Are there any tools?
-
Is it possible to catch
out of memory exceptionand based on memory usage do something, for example crash only request handlers exceeding assumed memory limit? If so, what could be bad with that?
To answer your first question, there are many tools which you can use to monitor memory usage, however i don’t know of any application which maps memory usage to threads in “real” time. Within the application you can use the MemoryMXBean and MemoryPoolMXBeans to monitor memory usage,
To answer your second question: no, not really. Besides the fact that it is generally a bad idea to catch OOME, the primary problem is that the thread which receives the exception may not be the actual culprit. the OOME is thrown on the thread which makes the final allocation request. however, some other thread could be the one which filled up most of memory. The other problem is that since OOME can be thrown at any time, it could be thrown inside some critical code within your application, leaving it in a crippled state. long story short, you pretty much always want to restart your application when you receive an OOME.