Neeraj Vij wrote:1.) is the above code correct for creating a thread safe singleton object ?
Well, the creation of the single instance is thread safe because you initialize it when the class is initialized, and class initialization is an atomic action. You'll need to make that single instance thread safe as well, e.g. by using synchronized instance methods.
2.) if yes, what will happen if 2 threads will use class.Forname to load the above class. will there be more than one instance.
It depends on where the class was loaded from:
- If the class is on the class path then the same Class instance will be used, so there will be only one instance.
- If the class is loaded using a different ClassLoader but using the same ClassLoader instance then the same Class instance will be used, so there will be only one instance.
- If the class is loaded using two different ClassLoaders then there will be two Class instances, and therefore two singleton instances.
You can
test the last example by using two different URLClassLoader objects to load the class, making sure the class is not on the class path. You can turn a File into a URL by using file.toURI().toURL():