相关疑难解决方法(0)

同步成本

在一个高度并发的Java程序中,并假设我的方法正确编写并正确同步,我想知道如何确定哪个更好:

void synchronized something() {
     ...
}
Run Code Online (Sandbox Code Playgroud)

要么

void something() {
     synchronized(this) {
         ...
     }
     // here do stuff no requiring synchronization
     .
     . // do computation 'A'
     .
     synchronized(this) {
         ...
     }
     // here do other stuff no requiring synchronization
     .
     . // do computation 'B'
     .
     synchronized(this) {
         ...
     }
}
Run Code Online (Sandbox Code Playgroud)

现在我意识到如果计算'A'和'B'需要花费很多时间,那么第二个版本显然更好.

然而,我的问题是:你知道第二个版本更高效吗?

第二个版本总是更快还是有几次获取/释放锁的隐藏成本?

如果我的计算'A'只是一些微不足道的事情,那该怎么办?

s.getString().substring( 0, 2 ).toLowerCase();
Run Code Online (Sandbox Code Playgroud)

java synchronization synchronized

10
推荐指数
1
解决办法
4612
查看次数

标签 统计

java ×1

synchronization ×1

synchronized ×1