JVM上的内存分配是无锁的吗
当你在Java中执行new Object()
时,jvm是使用无锁算法来分配内存还是需要锁定?
我在本例中指的 JVM 是 Hotspot VM。据我所知,它只需要增加一个指针即可超快速地分配内存。但在多线程的情况下,这个增量是否需要锁定或CAS?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于:)我相信,如果您使用
-XX:+UseTLAB
选项(这是 Peter 指出的 Sun/Oracle JVM 的默认设置),由于线程本地堆,它将在“快乐路径”中无争用。当然,如果由于没有足够的空间而需要垃圾收集,我们就会进入并行 GC 等领域,其中有各种实现,而且都非常复杂......当然,这种情况一直在发生。即使在“单堆”模型中,我也希望分配得到高度优化 - 与其说是获取正常意义上的锁,不如说是在可能的情况下执行原子增量。但我不能说我知道细节。
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.
如前所述,默认情况下使用 Tlab。 此术语表中描述了该行为,如下 有关大小
调整的更多详细信息此博客 &您在此博客中可能需要的所有详细信息。
简而言之,它是线程本地的,除非 TLAB 已满,在这种情况下您需要访问共享池,这是一个 CAS 操作。
另一个复杂的因素可能是这个错误,它描述了卡片标记中的错误共享,即本身不是锁,但会损害性能(如果这就是您询问锁定的原因)。看起来这个问题在java7中已经修复了。
as mentioned, default is to use a tlab. The behavious is described in this glossary as follows
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.