Javamex

Java discussion forum to accompany the Javamex web site.

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.

Views: 83

Reply to This

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service