同步成本 [英] Cost of synchronization

查看:56
本文介绍了同步成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a highly concurrent Java program and assuming that my methods are correctly written and correctly synchronized, I am wondering about how to determine which is better:

void synchronized something() {
     ...
}

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) {
         ...
     }
}

现在我意识到,如果计算'A'和'B'花费大量时间,那么第二种版本显然更好.

Now I realize that if computation 'A' and 'B' takes a lot of time, the second version is obviously better.

但是,我的问题是:您何时知道第二个版本更有效?

My question, however, is : at which point do you know that the second version is more efficient?

第二个版本是否总是更快,或者多次获取/释放锁是否存在隐性成本?

Is the second version always faster or is there an hidden cost about acquiring/releasing the lock several times?

如果我的计算"A"只是像这样的琐碎的事情怎么办:

What if my computation 'A' is simply something trivial like:

s.getString().substring( 0, 2 ).toLowerCase();

推荐答案

是的,同步需要花费时间.如果实际计算很简单并且在一个循环之内,那么与实际计算相比会花费很多时间.

Yes, synchronized costs time. If the actual computations are simple and it's inside a loop or so, it costs lots of time compared to the actual computations.

请参见以下示例: http://ideone.com/zgpB7

  • 内部同步:大约0.025s
  • 整个循环同步:少于0.001秒

要确定哪种程序更适合您的程序,请让其执行操作并查看哪个时间更快.

To determine which one is better for your program, let it perform stuff and look at which time it's faster.

这篇关于同步成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆