Agile
A programmer's note
-
Don't use String literals for the synchronized blocks! - [转载]
2007-06-01
这个问题绝对是高人才能察觉的问题 ,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,随机文章:
HashMap.get() can cause an infinite loop! 2008-07-06Apache MINA竟然源自Netty2 2008-03-05epoll selector 2008-01-18RMI JDK6比JDK5强的地方 2008-01-03A hash set puzzler 2007-12-24
收藏到:Del.icio.us






