[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[转帖]不要用字符串做同步锁Don't use String literals for the synchronized blocks

上一篇:[转帖]java写二进制文件考虑一下字节顺
下一篇:[转帖]负数的表示形式,关于原码和补码的知识

添加日期:2011/6/3 17:15:18 快速返回   返回列表 阅读4795次
这个问题绝对是高人才能察觉的问题 ,Groovy的实现中就用了string.inner()作为锁来作同步的,开始我认为这是一个很高明的技巧,今天看了这个文章又觉得幸亏我看了~_~

转自:http://www.javalobby.org/java/forums/t96352.html

Code that is using String literals to synchronize on is dangerous. 
See the example below:

class Foo  {
  static private final String LOCK = "LOCK";
  void someMethod() {
    synchronized(LOCK) {
    ...
    }
  }
}

Why is this dangerous? I have a nice private String which is mine and mine alone? Or is it?  No, it isn't! 

Recall section 3.10.5 of the Java Language Spec 2.0: 
It says among other things: 
"Literal strings within different classes in different packages likewise represent references to the same String object." 

For the code above this means that any number of foreign classes can contain the same literal which translates to the same object, hence creating potential dead-lock situations! 
This is also true for Strings for which you call the intern() method! 

And this is not only a nice theory, something like this really happened between our code and code in the Jetty library. Both sections used the same string literal above to synchronize critical code sections. The two code segments created a dead-lock with very puzzling stack traces  
(The Jetty-Bug has been reported already, btw, Jetty-352) 

If you really need an object for locking purposes, just create a new Object() to lock on. 
Also consider various alternatives, namely using this or facilities in the java.util.concurrent package. 

Cheers,
-------------------------------------
大概意思就是,两个类里如果用了同一个字符串做为同步锁,那么它们两个可能互相锁。

字符串,同样的内容,对应的是同一个String对象。
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved