wood burning stoves*
The moose likes Java in General and the fly likes Singleton Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Singleton Issue" Watch "Singleton Issue" New topic
Author

Singleton Issue

Neeraj Vij
Ranch Hand

Joined: Nov 25, 2003
Posts: 315
Hi,

I have the following java code for creating a thread safe singleton.



please provide inputs for the following -

1.) is the above code correct for creating a thread safe singleton object ?

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.

Thanks
Neeraj
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

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():


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

For most common uses, yes your class is threadsafe

But you could take steps to avoid multiple classloaders to load the class

Depends upon your requirements. There is also a way to break singleton by reflection


Java Experience
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton Issue
 
Similar Threads
Why constuctor can't be marked as final?
Synchronization for Singleton
Initialize-On-Demand idiom vs simple static initializer in Singleton implementation
Singleton Class
Restricting the number of objects