NOTE: This question is not about Singleton classes as described in Gamma94 (ensuring only one object ever gets instantiated.)
I read the Guice documentation about the @Singleton attribute:
Classes annotated @Singleton and @SessionScoped must be threadsafe.
Is this the case even if I don’t intend to access the object from more than one thread? If so, why?
If an object is only ever accessed from a single thread, it doesn’t need to be threadsafe even it’s a Guice
@Singleton. Guice doesn’t do any multithreading internally that could cause a non-threadsafe singleton to break… the process of building theInjectoris all done on the thread that callsGuice.createInjectorand any dynamic provisioning is done on the thread that callsprovider.get(). Of course, a singleton is only going to be created once and then just returned each time it’s needed… when it’s created depends on whether it’s bound as an eager singleton (always created at startup) and whether theInjectoris created inStage.DEVELOPMENT(created only if and when needed) orStage.PRODUCTION(created at startup).It’s very often the case that singletons can be accessed from multiple threads at the same time though (particularly in web applications), hence the warning. While many developers will understand that a singleton needs to be threadsafe in that case, others may not and I imagine it was considered worth it to warn them.