这个问题绝对是高人才能察觉的问题 ,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对象。
|