Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is memory allocation on the JVM lockless

When you do a new Object() in Java, does the jvm use a lockless algorithm to allocate memory or does it need to lock?

The JVM I am referring to in this case is the Hotspot VM. From the little I know about it, it just needs to increment a pointer to allocate memory super fast. But in the case of multiple threads, does that increment require locking or CAS?

like image 564
pdeva Avatar asked Nov 16 '11 06:11

pdeva


People also ask

Does JVM allocate memory?

JVMs allocate memory on an as needed basis from the operating system. Generally, when the JVM starts, it will allocate the minimum memory allocated (Xms) to the application that is running. As the application requires more memory, it will allocate blocks of memory until the maximum allocation (Xmx) has been reach.

Where is the memory allocated for the JVM?

Heap memory is the run time data area from which the memory for all java class instances and arrays is allocated. The heap is created when the Java Virtual Machine starts up and may increase or decrease in size while the application runs. The size of the heap can be specified using –Xms VM option.

How does JVM manage memory?

JVM Memory Structure. JVM creates various run time data areas in a heap. These areas are used during the program execution. The memory areas are destroyed when JVM exits, whereas the data areas are destroyed when the thread exits.

Does JVM use malloc?

The JVM (like any other process) will call the C runtime malloc function in order to allocate memory from the operating system and then manages the heap for the Java application.


1 Answers

as mentioned, default is to use a tlab. The behavious is described in this glossary as follows

TLAB
Thread-local allocation buffer. Used to allocate heap space quickly without synchronization. Compiled code has a "fast path" of a few instructions which tries to bump a high-water mark in the current thread's TLAB, successfully allocating an object if the bumped mark falls before a TLAB-specific limit address.

Further details on sizing in this blog & all the details you could want in this blog.

In short it's thread local unless the TLAB is full in which case you'll need to hit the shared pool and this is a CAS operation.

Another complicating factor could be this bug that describes false sharing in card marking which is not a lock as such but will hurt performance (if this is why you're asking about locking). It looks like this is fixed in java7 though.

like image 94
Matt Avatar answered Oct 20 '22 17:10

Matt