Double Checked Locking
Wednesday, April 16th, 2008今日係 newsgroup 見到個 singleton 問題:
// 版本 A
public static synchronized Socket getInstance ( )
throws IOException {
if ( instance == null || instance.isClosed ( ) ) {
instance = new SingleSocket ( ) ;
}
return instance ;
}
// 版本 B Double-check Locking
public static Socket getInstance ( )
throws IOException {
if ( instance == null || instance.isClosed ( ) ) {
synchronized ( instance ) {
if ( instance == null || instance.isClosed ( ) ) {
instance = new SingleSocket ( ) ;
}
}
}
return instance ;
}
經過唔同人既 comment, 原來版本 B 係唔 work 的, 詳情請見 Ref: Double Checked Locking
