5

I am reading that the playframework is removing global state that is in older 2.4.x versions.

Can someone explain where the global state currently is and what are the benefits of removing global state?

1

1 Answer 1

1

What is the global state?

There is an object play.api.Play with the following field:

@volatile private[play] var _currentApp: Application = _

Where is it used?

Whenever you do Play.current you refer to that single mutable global field. This is used all across the framework to access things such as:

  • play.api.Play.configuration takes an implicit app
  • play.api.libs.concurrent.Execution.defaultContext calls the internal context, which uses the currently running app to get the actor system
  • play.api.libs.concurrent.Akka.system takes an implicit app
  • play.api.libs.ws.WS.url takes an implicit app
  • and many more places..

Why is that bad?

A number of functions just take an implicit app, so that's not really global state, right? I mean, you could just pass in that app. However where do you get it from? Typically, people would import play.api.Play.current.

Another example: Let's say you want to develop a component that calls a webservice. What are the dependencies of such a class? The WSClient. Now if you want to get an instance of that, you need to call play.api.libs.ws.WS.client and pass in an application. So your pretty little component that logically only relies on a webservice client, now relies on the entire application.

Another big factor and a direct consequence of the previous point is testing. Let's say you want to test your webservice component. In theory, you'd only need to mock (or provide some dummy implementation of) the webservice client. However now that somewhere in your code you're calling play.api.Play.current, you need to make sure that that field is set at the time it is called. And the easiest way to ensure that is to start the play application. So you're starting an entire application just to test your little component.

2
  • isnt' global state now gone in the latest version of play?
    – Blankman
    Nov 25, 2016 at 22:33
  • The latest version is play 2.5, which deprecates Play.current (ie. the access to the current application). However there are still a few of places where it is used. Not relying on this anymore will incur API changes, which is why a number of "intermediate" releases are made towards the goal of becoming fully stateless (it that would be 3.0).
    – rethab
    Nov 26, 2016 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.