0

Singleton class in java means a class which can be initialized only once and all the classes will use the same object. Only one object will be create for everyone. But my question is when more than one threads will be there to initialize the same object at the same time what will be happened there? Will there be two or more objects? How can we restrict this?

  • 1
    The most popular implementation of `Singleton` is not thread-safe. Use synchronization in `newInstance` method. But when you create instance in `static{}` block, then is thread-safe. – Areo Nov 09 '13 at 09:33
  • @Areo: I've seen more people use thread-safe implementations than unsafe ones... I'm not sure what kind of "popular" you're talking about here. – Jon Skeet Nov 09 '13 at 10:06
  • @Jon Skeet: I mean `popular` solution as class with private constructor and `newInstance` method. In this method you check if static `instance` filed is `null`. if yes then create a new instance and assign to static field. – Areo Nov 09 '13 at 10:09
  • @Areo: If the static method is synchronized, that's fine - but I haven't seen that approach used very much, thankfully. Maybe it's just where I've worked, but it's pretty *obviously* not thread-safe in that unsynchronized form, and there are enough resources on the net which show how to do it properly that I'm surprised you've found more examples of that broken approach than any other. – Jon Skeet Nov 09 '13 at 11:41
  • @Arnav Kumar refer http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/71399#71399 – Dev Blanked Nov 09 '13 at 13:13

1 Answers1

2

But my question is when more than one threads will be there to initialize the same object at the same time what will be happened there? Will there be two or more objects? How can we restrict this?

Multiple ways to achieve it:

  1. Synchronization can be used to control the creation of multiple objects for a singleton class in a multi-threaded environment.

  2. Creation of singleton object during class loading using static blocks.

Wiki describes the way to write Singleton class in an excellent manner considering multi-threaded environment as well.

http://en.wikipedia.org/wiki/Singleton_pattern

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136