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
I've briefly described the allocation procedure in HotSpot JVM in this answer.
The way how an object is allocated depends on the area of the heap where it is allocated.
TLABs are the areas in Eden reserved for thread-local allocations. Each thread may create many TLABs: as soon as one gets filled, a new TLAB is created using the technique described in #2. I.e. creating of a new TLAB is something like allocating a large metaobject directly in Eden.
Each Java thread has two pointers: tlab_top and tlab_limit. An allocation in TLAB is just a pointer increment. No synchronization is needed since the pointers are thread-local.
if (tlab_top + object_size <= tlab_limit) {
new_object_address = tlab_top;
tlab_top += object_size;
}
-XX:+UseTLAB is enabled by default. If turn it off, the objects will be allocated in Eden as described below.
If there is not enough space in TLAB for a new object, either a new TLAB is created or the object is allocated directly in Eden (depending on TLAB waste limit and other ergonomics parameters).
Allocation in Eden is similar to allocation in TLAB. There are also two pointers: eden_top and eden_end, they are global for the whole JVM. The allocation is also a pointer increment, but atomic operations are used since the Eden space is shared between all threads. Thread-safety is achieved by using architecture-specific atomic instructions: CAS (e.g. LOCK CMPXCHG on x86) or LL/SC (on ARM).
This depends on GC algorithm, e.g. CMS uses free lists. Allocation in Old Generation is typically performed only by Garbage Collector itself, so it knows how to synchronize its own threads (generally with the mix of allocation buffers, lock-free atomic operations and mutexes).