Let's assume this is about to happen in a true parallel environment, one VM, at the same time:
// Thread 1:
new Cat()
// Thread 2:
new Dog()
// Thread 3:
new Mouse()
How does JVM ensure thread safety of memory allocations on heap?
Heap is one for all threads and it has its own internal data.
For simplicity assume a simple compacting garbage collector implementation, -XX:+UseSerialGC -XX:+UseParallelGC, with simple incremental pointer to mark a start of free space and one continuous free space in Eden (heap).
There must be some kind of synchronization between threads when heap space is allocated for Cat, Dog and Mouse instances otherwise they can easily end up overwriting each other. Does that mean that every new operator hides inside some synchronized blocks? This way, many "lock free" algorithms are not in fact completely lock free ;)
I assume that memory allocations are made by the application thread themselves, synchronously, not by another dedicated thread(s).
I am aware of TLABs, or Thread Local Allocation Buffer. They allow threads to have a separate memory areas in Eden for allocations, so no synchronization is required. But I am not sure if TLAB is set by default, it is somewhat very obscure HotSpot feature. Note: do not confuse TLAB and ThreadLocal
variables!
I also assume, that with more complex garbage collectors, like G1, or non-compacting garbage collectors, more complex heap structure data has to be maintained, like list of free blocks for CMS, so more synchronization is needed.
UPDATE: Please let me clarify this. I accept answer for HotSpot JVM implementation and variants with and without active TLAB.
UPDATE: According to my quick test, TLAB are set ON by default, on my 64-bit JDK 7, for Serial, Parallel and CMS garbage collectors, but not for G1 GC.