I have read the stuff about this question in this website. But I'm still confused about the DCL(Double-Checked locked). I don't know how it works well after java 5. Here is the code of DCL:
public class MyFactory {
private static volatile MyFactory instance;
public static MyFactory getInstance(Connection conn)
throws IOException {
if (instance == null) {
synchronized (MyFactory.class) {
if (instance == null)
instance = new MyFactory(conn);
}
}
return instance;
}
private MyFactory(Connection conn) throws IOException {
// init factory using the database connection passed in
}
}
Let me give an example:
private volatile int i = 0;
since i++ is not a atomic operation, how can we make sure that it can work well in the DCL. I mean if the thread execute ''instance = new MyFactory(conn);', how can it works well. Can someone give me details.