Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton Issue

 
Neeraj Vij
Ranch Hand
Posts: 315
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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():
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic