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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With