Using thread or process memory in Java

In my application, I run some threads with untrusted code, so I need to prevent memory overflow. I have a WatchDog that analyzes the time of the current thread (threads were called in sequential order). But how can I determine memory usage? I only know the memory usage of the entire virtual machine using Runtime.totalMemory() ? If you can learn about using a thread or using a single process, it would be great. Using memory in the process, I could still calculate the use of the thread.

+6
source share
3 answers

Since the JVM running the Java program is a Java process, you need not worry about it. All threads use the same memory space in the JVM process.

Therefore, it is enough to rely on

+2
source

A Java application cannot control the amount of memory or (or CPU) used by its threads, whether the threads are trusted or untrusted code. There is no API to do this in existing generations of JVMs. And, of course, there are no APIs to monitor the use of threads in memory. (It’s not even clear that this is a meaningful concept ...)

The only way to guarantee the use of resources of untrusted Java code is to run the code in a separate JVM and use operating system level resource controls (such as ulimit, nice, sigstop, etc.) and "-Xmx" to limit the use of JVM resources.


Some time ago, Sun produced the JSR 121 , which aimed to solve this problem. This JSR will allow you to divide the application into parts (called "isolates"), which are transmitted through messaging, and offered the ability to isolate one to control and manage the other. Unfortunately, Isolate APIs are not yet implemented in any core JVM.

+1
source

What you need to do is run untrusted code in your own / JVM process. This is possible using JNI interfaces (if your operating system allows it).

0
source

Source: https://habr.com/ru/post/910536/


All Articles