Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). But how i can determine the memory usage? I only know the memory usage of the whole VM with Runtime.totalMemory()? 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.

like image 374
Nicolas Avatar asked Mar 12 '12 20:03

Nicolas


People also ask

How much memory does a thread use Java?

Be mindful of thread use and stack size. The default option -Xss512k means that each thread will use 512kb of memory. The JVM default without this option is 1MB.

Which memory is used by thread?

We talked about the two types of memory available to a process or a thread, the stack and the heap. It is important to distinguish between these two types of process memory because each thread will have its own stack, but all the threads in a process will share the heap.

Does thread consume memory?

Threads generally consume from a shared memory. Hence threads do not own any specific memory.

What is memory usage in Java?

A MemoryUsage object represents a snapshot of memory usage. Instances of the MemoryUsage class are usually constructed by methods that are used to obtain memory usage information about individual memory pool of the Java virtual machine or the heap or non-heap memory of the Java virtual machine as a whole.


1 Answers

Since a JVM executing a Java program is a Java process you don't have to worry about that. All threads share the same memory space in the JVM process.

Hence it is sufficient to rely on

  • Runtime.totalMemory()
  • Runtime.freeMemory()
like image 84
Konrad Reiche Avatar answered Nov 05 '22 14:11

Konrad Reiche