Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amount of memory useage when creating Java threads

How much memory (roughly) is allocated when a Java thread is instantiated and started?

Here's a code sample:

// Definition of the thread class
class BasicThread extends Thread {
    // This method is called when the thread runs
    public void run() {
    }
}
.
.
.
// Create and start the thread
Thread thread = new BasicThread();
thread.start();
like image 593
Armond Mehrabian Avatar asked Jun 14 '11 17:06

Armond Mehrabian


People also ask

How much memory does a Java thread take?

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.

Do threads consume memory?

Threads generally consume from a shared memory. Hence threads do not own any specific memory. If any threads work on a scope with variables, a memory profiler would help you get that information.

Which memory is used in threads Java?

2. Stack Memory in Java. Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.

How much memory should I allocate to Java?

When allocating memory to a JVM, 10% to 25% of the memory is for the JVM process itself and the remainder is for the code running in the JVM. This means that a JVM that has been allocated 4 GB may only have 3.5 GB available to the code running in the JVM. This resource memory used by the JVM is often called overhead.


1 Answers

Well the thread (that is the object) itself needs some space - it does have a dozen or so variables and objects (and I'm way too lazy to count them correctly) but it should be little more than maybe 200byte (you'd basically have to count all primitives and references [trivial, those have fixed sizes - but references depend on your VM] and then compute the size of all objects that are allocated by the class [the hotspot VM has an overhead of 2 words per object (3 if there are no local variables in the object) and allocates on an 8byte boundary])

What really takes space is the thread local stack and that can be affected by the -Xss flag to the VM (although note that every OS has some limitations to the maximum stackspace, you can influence this with -ulimit in linux and surely somehow in windows as well).

The defaults for hotspot are as follows:

In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.

On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.

like image 182
Voo Avatar answered Oct 21 '22 01:10

Voo