Search code examples
javaweb-servicesdesign-patternsspring-bean

Static variable vs singleton


I'm making Java REST application. I wonder how should I implement my services - should I use static service variables for whole application or make services as singletons like it was made in Spring MVC. Is there any difference between singleton object and initializing object only once during application?


Solution

  • should I use static service variables for whole application or make services as singletons

    It depends. You have to ask yourself two questions to come up with an answer:

    Where is that static variable stored?

    You have 2 Options:

    1. Declare a final class Services which holds all available services as public static final variables.
    2. Create in every service class a public static final variable, called INSTANCE

    You see that the first point will have all classes in the same place. Could possibly get clustered, unreadable and not very easy to maintain.

    For the second point you're almost approaching the singleton case.

    Do I need to initialize a service lazily or eagerly?

    You again have 2 Options:

    1. Lazily: use the static holder pattern to initialize the singleton lazily the first time it is used
    2. Eagerly: create a public static final variable in the service class and create an instance directly.

    The first point has it's upsides. If you need to allocate resources or need to do any other "heavy" operation. This works, and is thread safe

    For the second point you see that it's like the second point from the first question.

    Conclusion

    As said, it depends on the use case. I would probably use a singleton always. Because then all the logic regarding it's state and availability are all held in one place.