3 ms·
People also bash singletons, so you can't really win. You can get issues with a singleton being accessed for the first time from multiple threads at once, for
by w0mbat 5y ago
People also bash singletons, so you can't really win.
You can get issues with a singleton being accessed for the first time from multiple threads at once, for example, so you end up with more than one instance being created or a situation where one thread triggers the creation and another accesses before it has been fully initialized, depending on the code.
- throwaway889900 5y agoIf you expect that sort of thing to occur, then your get method should be synchronized to prevent it.
- dcow 5y agoThese days in both Java and Swift you can just lazily reference a static class field/property set to an instance of the singleton (in java the field must be on a dedicated private class) and the Runtime will lazily initialize it exactly once in a thread-safe manner the first time it is referenced.
- w0mbat 5y agoThat's only the tip of the iceberg I'm afraid. If the singleton has methods that perform actual work asynchronously and different threads are hammering on it, all kinds of issues come up. Of course a seasoned developer is going to acticipate this and write the needed infrastructure, but a newbie is not. It can be better if different threads have their own worker objects with their own state for example.