Why use singlet controllers in game 2.5?

I am just starting, and I donโ€™t think I understand it very well. From what I understand, all controllers are created as dependencies at the time the router was created. Then they live until the router dies when the application stops. If so, declaring them to be solitary seems redundant.

+5
source share
2 answers

To get rid of the global state (which contradicts the idea of โ€‹โ€‹a stateless design) Play introduced DI (I think, about v2.4), and in version 2.5 it uses an embedded router by default. Google Guice is a standard DI environment packaged in Play (you can use others, but Guice by default).

Now (in general) Guice believes that creating new Controller instances is faster and more thread-safe than using singleton - see Guice docs for more .

If you need to limit the controller instances to only 1, then you can mark it with a single, but you must make it Thread-safe , as it will be transferred between threads.

I think Activator templates could do a bit more documentation with them to explain why they seem to generate @Singleton controllers when they don't seem to be needed, as this is confusing. HomeController (in the seed of a Play-Scala), for example, is declared perplexed by @Singleton when it does not have for this occasion.

In general, it is best not to use @Singleton unless you have a fair understanding of thread immutability and security. If you think you have a use case for Singleton, just make sure that you are protecting some kind of general condition.

In short, do not use @Singleton .

+5
source

If you have a controller created by the router (that is, by default), then they are implicitly single-point because the router exists only once. However, if you add the controller to another location, you will still receive a new instance if it is not marked as singleton.

Source: https://github.com/playframework/playframework/issues/4508#issuecomment-127820190

+1
source

Source: https://habr.com/ru/post/1259865/


All Articles