0

In our project, we often use a utility class and its static methods to load some icons. This utility class is singleton.

But in the running environment, we find 314 instances of this class, under which circumstances does that occur?

NotMe
  • 87,343
  • 27
  • 171
  • 245
zhaoyw
  • 31
  • 2
  • Food for thought: http://stackoverflow.com/q/70689/758280 – Jeffrey Nov 27 '11 at 02:49
  • @zhaoyw Then it is not a singleton by definition nor implementation. If you are just using static methods and resources then really it doesn't even sound like you need a singleton, just a static library of methods. The ONLY reason to use a singleton is when some type of state needs to be maintained that logically belongs to the singleton and the said object in question needs to be guaranteed to be instantiated only once. – Matthew Cox Nov 27 '11 at 03:46

3 Answers3

8

A static utility class isn't quite the same as a singleton class. (A singleton class is where there is exactly one instance and you access its instance methods, not static methods.) If you don't want instances of your class being created, make sure there is at least one declared constructor and that all constructors are declared private. All places where you are creating instances should then light up as compiler errors.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • sorry! it is not a singleton class, but it implements like this: class XXX{ private XXX(){} ... all of methods and fields are static} – zhaoyw Dec 03 '11 at 02:13
  • @zhaoyw - If you have a private constructor (and no public constructors), then I think the only way you end up with hundreds of instances of your class is if some code in the class itself (one or more of those static methods) is creating them. Check your static methods for any `new` operators. – Ted Hopp Dec 03 '11 at 23:05
1

When more than one class loader is involved.

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • we know the classloader of jvm. If one or more classloader happens, the number will be 314? – zhaoyw Nov 27 '11 at 02:40
0

Could you post your implementation? It sounds like you are instantiating the static class multiple times. Is your constructor private? Are you implementing the getInstance method correctly?

vishal
  • 895
  • 1
  • 9
  • 25