J2EE gives us a structured (constrained?) architecture for application design. One of the guidelines to using this structure is to keep state in servlets and stateful session beans, making the rest of the application stateless. My issue is with how then to access this state from other parts of my application efficiently.
I want to pass something that will allow access to the state, rather than elements of the state itself as this would require me to know all the elements that are needed by any subsequent called code, so breaking encapsulation.
I have some specific requirements but this seems to be a general. Specifically I want to pass a unique id through my code to allow correlation of all log entries; a mechanism to access a buffer that is 'private' to my 'thread' of execution; to be able to pass generally useful parameters e.g. current user id; to accumulate performance metrics relating to the 'thread' of execution.
I can only see a couple of ways to do this. One not very elegant, but reliable. The other (arguably) more elegant, but with associated risks. Firstly pass a parameter to every single one of my methods, through which the state be accessed. Secondly pass a parameter at well defined points only, ensuring that the value is stored in a ThreadLocal (and therefore available to any of my code in this 'thread' of execution). Note these well defined points may be hard to define, and even harder to police.
So, if anyone has any insight to offer that would be much appreciated. Failing that does anyone else see this as an issue, and perhaps something that the app. container should provide.