This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Singleton Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply 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: 19216

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
How To Ask Questions How To Answer Questions
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 446

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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Singleton Issue
 
Similar Threads
Singleton Class
Synchronization for Singleton
Why constuctor can't be marked as final?
Initialize-On-Demand idiom vs simple static initializer in Singleton implementation
Restricting the number of objects