Monday, August 17, 2009

Pattern: InvocationContext Propagation

Another good name for this pattern might be ThreadLocal Encapsulation.

This pattern is a real ThreadLocal killer as it is a way to track state over several calls without widespread ThreadLocal usage.

Internally in OpenEJB we have managed to boil all our ThreadLocal usage down to this sort of "one to rule them all" approach. When attempting to describe it to a user I started using the javax.interceptor.InvocationContext as an example. The result was an ejb3 design pattern that is too cool not to share.

Add the following Interceptor as a global interceptor at the beginning of the interceptor stack.
The Interceptor uses a private ThreadLocal to propagate invocation state by linking the InvocationContext objects together. The result is that you can do an infinite amount of state tracking as well as write some pretty impressive diagnostic tools.

Anyone downstream of this interceptor can make a call like this to get access the an infinite amout of state up the stack. You can move specific state forward for quick access. You can also look infinitely back the invocation chain for state set in a previous InvocationContext. Or perhaps more elegantly as a recursive method. A JavaDoc'ed and ASL licensed version here: http://gist.github.com/168153

1 comment:

.:raPHa:. said...

Hi David, I am implementing an auditor for EJBs methods and need a solution like this to record the call stack between methods in enterprise application.
This mechanism is safe for concurrent calls?