Is memory allocation on the JVM lockless
Asked Answered
G

2

9

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?

Ganger answered 16/11, 2011 at 6:56 Comment(0)
D
5

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.

Dirkdirks answered 16/11, 2011 at 10:33 Comment(0)
D
4

It depends :) I believe that if you use the -XX:+UseTLAB option (which is the default for Sun/Oracle JVMs as noted by Peter), it will be contention-free in the "happy path" due to thread-local heaps. Of course, if garbage collection is required due to there not being enough space, we get into the territory of parallel GCs etc, where there are various implementations and it's all very complicated... and of course, this moves on all the time.

Even in the "single heap" model, I'd expect the allocation to be highly optimized - not so much acquiring a lock in the normal sense as performing atomic increments where possible. I can't say I know the details though.

Dabster answered 16/11, 2011 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.