简体   繁体   English

Java中线程或进程的内存使用情况

[英]Memory usage of thread or process in Java

In my application i run some threads with untrusted code and so i have to prevent a memory overflow. 在我的应用程序中,我使用不受信任的代码运行一些线程,所以我必须防止内存溢出。 I have a WatchDog wich analyses the time of the current thread (the threads were called in serial). 我有一个WatchDog,它分析当前线程的时间(线程是串行调用的)。 But how i can determine the memory usage? 但我如何确定内存使用情况? I only know the memory usage of the whole VM with Runtime.totalMemory() ? 我只用Runtime.totalMemory()知道整个VM的内存使用情况? If there is a possibility to find out the usage of the thread, or the usage of the single process it would be great. 如果有可能找出线程的使用,或单个进程的使用,那将是很好的。 With the memory usage of the process i could calculate the usage of the thread anyway. 通过进程的内存使用,我可以计算线程的使用情况。

Since a JVM executing a Java program is a Java process you don't have to worry about that. 由于执行Java程序的JVM是Java进程,因此您不必担心这一点。 All threads share the same memory space in the JVM process. 所有线程在JVM进程中共享相同的内存空间。

Hence it is sufficient to rely on 因此,依靠它就足够了

A Java application cannot control the amount of memory or (or CPU) used by its threads, irrespective of whether the threads are running trusted or untrusted code. 无论线程是运行可信代码还是不可信代码,Java应用程序都无法控制其线程使用的内存量或(或CPU)。 There are no APIs for doing this in current generation JVMs. 在当前一代JVM中没有用于执行此操作的API。 And there are certainly no APIs for monitoring a thread's usage of memory. 当然没有用于监视线程内存使用情况的API。 (It is not even clear that this is a meaningful concept ... ) (甚至不清楚这是一个有意义的概念......)

The only way you can guarantee to control the resource usage 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 that JVM's resource usage. 您可以保证控制不受信任的Java代码的资源使用的唯一方法是在单独的JVM中运行代码,并使用操作系统级资源控制(例如ulimit,nice,sigstop等)和“-Xmx”来限制JVM的资源使用情况。


Some time back, a Sun produced JSR 121 aimed at addressing this issue. 一段时间以来,Sun制作了旨在解决这个问题的JSR 121 This JSR would allow an application to be split into parts (called "isolates") that communicated via message passing, and offered the ability for one isolate to monitor and control another. 这个JSR允许将应用程序拆分为通过消息传递进行通信的部分(称为“隔离”),并为一个隔离提供监视和控制另一个隔离的能力。 Unfortunately, the Isolate APIs have yet to be implemented in any mainstream JVM. 不幸的是,Isolate API尚未在任何主流JVM中实现。

What you need to do is to run the untrusted code in its own process/JVM. 您需要做的是在自己的进程/ JVM中运行不受信任的代码。 This is possible using the JNI interfaces (if your operating system permits it). 这可以使用JNI接口(如果您的操作系统允许)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM