How are singletons handled in a web application?

前端 未结 4 1032
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 10:35

From what I understand, a singleton is basically when you have a private member that represents the object you want to have a single instance for. Then in the constructor y

4条回答
  •  我在风中等你
    2020-12-14 10:45

    Yes, there's a singleton pattern, which works as you describe. It's problematic and comes with caveats as mentioned by Stephen C above. If you need single instance data your best option is to have it built by a spring container (or other containers that support this), which will handle the instantiation (which is much more problematic than you might think).

    If you must roll your own, read up thoroughly on the double-checked locking idiom and the issues that come with it to understand the issues that can come up with singleton instantiation. If your instantiation is non-trivial it's actually very easy to get multiple instances or race conditions in instantiation. I've done it myself. In production (but it was a long time ago ;) )

提交回复
热议问题