当您使用Java执行new Object()时,jvm是否使用无锁算法来分配内存,还是需要锁定?

在这种情况下,我指的是Hotspot VM。据我所知,它只需要增加一个指针就可以超快地分配内存。但是在有多个线程的情况下,该增量是否需要锁定或CAS?

最佳答案

如前所述,默认是使用tlab。行为在this glossary中描述如下

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.

有关在this blog中调整大小的更多详细信息,以及在this blog中可能需要的所有详细信息。

简而言之,除非TLAB已满,否则它是本地线程,在这种情况下,您需要访问共享池,这是CAS操作。

另一个复杂的因素可能是this bug,它描述了卡标记中的错误共享,它不是锁,而是会损害性能(如果这就是为什么您要问锁的原因)。看起来这在java7中是固定的。

10-05 19:41