gpt4 book ai didi

java:一个同步与更多同步围绕相同的代码

转载 作者:行者123 更新时间:2023-12-03 18:41:52 24 4
gpt4 key购买 nike

一个同步比很多同步好吗?

synchronized(this)
{
CODE1
CODE2 // uncritically code, short duration
CODE3
CODE4 // uncritically code, short duration
CODE5
}

对比

synchronized(this)
{
CODE1
}

CODE2 // uncritically code, short duration

synchronized(this)
{
CODE3
}

CODE4 // uncritically code, short duration

synchronized(this)
{
CODE5
}

以下适用:同步块(synchronized block)尽可能小,就像我在第二个示例中编写的那样。

但这无论如何都是正确的吗?如果不加批判的代码片段持续时间很短,如果我不锁定解锁锁定解锁等等,也许我的程序性能更高?

最佳答案

如果有助于提高性能,JVM 的优化器能够连接相邻的同步块(synchronized block),但它不能做相反的事情,因为拆分它会改变语义。

请参阅 Java SE 6 性能白皮书,2.1.2 Lock coarsening

There are some patterns of locking where a lock is released and then reacquired within a piece of code where no observable operations occur in between. The lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations in those situations […]. It basically reduces the amount of synchronization work by enlarging an existing synchronized region.

对 Java 6 的引用表明这甚至不是一个全新的功能
因此,如果您知道存在不重要的代码并且整个代码都在临时释放锁(可能会在其他线程之间更改状态),那么请使用多个同步块(synchronized block),告诉 JVM 和人类读者 CODE2 和CODE4 不重要。

这遵循让运行时优化器做出正确权衡的典型模式,因为它比我们更了解实际情况,即硬件和实际应用程序行为。

关于java:一个同步与更多同步围绕相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59377937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com