0

I have singleton in Java and I have realized, that I could make its fields static and it would work same way as regular instance fields.

Would there be a performance / optimization difference? If so, what would turned out better? Is there a preferred way to implement singleton fields? (again, I am talking fields, not methods)

Lukáš Rutar
  • 161
  • 1
  • 5
  • 1
    keep them per instance, for reasons discussed several times before here, for example in [Make methods that do not depend on instance fields, static?](http://programmers.stackexchange.com/questions/215826/make-methods-that-do-not-depend-on-instance-fields-static) and in [Which is a better practice - helper methods as instance or static?](http://programmers.stackexchange.com/questions/111938/which-is-a-better-practice-helper-methods-as-instance-or-static) – gnat Apr 19 '14 at 09:58
  • 1
    @gnat thanks for answer, But I found that both your links refer to use of static methods. And I was asking about static fields... – Lukáš Rutar Apr 19 '14 at 10:00
  • sure. I think reasoning is essentially the same – gnat Apr 19 '14 at 21:00
  • The preferred way of dealing with singletons is to avoid them. – Doval May 20 '14 at 11:52

2 Answers2

1

Keep in mind that static does not mean unique in the entire application. It is just unique for the classloader. If you are working with multiple classloaders in an application server for example there will be multiple values for the same field.

Instead of the static approach you should take a look into dependency injection which would give you what you need without the problems of singletons and static attributes.

Lukei
  • 144
  • 5
0

Yes, there could be a performance difference. If you were, for example, to write a class for a Logger, and in the entire runtime of the application you never logged anything, then you wouldn't have needed to initialize the logger. If you wrote this class as static, then you would initialize it at the beginning of the program regardless of whether you use it. If you were to create it as a singleton, you could perform lazy initialization, which solves this issue.

In terms of the "Preferred Way," from what I've heard, it is preferred to implement it as a Singleton or similar if your object has state, and static if otherwise. This is to improve testability, because testing a static object with state is a pain in the butt, and it isn't reliable. But that is for a different question.

In your case, with fields, the answer is definitely to go with a singleton unless you have strong reason to do otherwise.

Kyranstar
  • 101
  • 1
  • 2