4 ms·
If you expect that sort of thing to occur, then your get method should be synchronized to prevent it.
by throwaway889900 5y ago
If 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.