Ohad Schneider Ohad Schneider - 1 year ago 111
Java Question

Flow execution/logical context across async calls

Is there a mechanism in Android (Java) to retain logical context, similar to .NET's

? By logical context I mean information that once retained, is later accessible across the entire logical thread of execution, meaning it will survive async calls. For example:

handler = new Handler();

final Runnable r = new Runnable() {
public void run() {
System.out.print(LogicalContext.get("foo")); //should print "bar"

LogicalContext.set("foo", "bar");
handler.postDelayed(r, 1000);

To clarify, I know about closures. What I need however is an automatic mechanism that will not require me to capture the context I want to pass every time. To further clarify, a mere static field won't do either, as I would want different logical threads of execution to have different contexts (which would start when I call
and flow [essentially by copying] through any async call made from then on).

In C# it would look like this:

CallContext.LogicalSetData("foo", "bar");
await Task.Run(() => Console.WriteLine(CallContext.LogicalGetData("foo")));

If that's impossible, I would settle for a special case of this mechanism - determine whether the current logical flow/thread of execution originated from an

Answer Source

You can use InheritableThreadLocal<T>, which is similar to .NET's AsyncLocal<T>:

Handler handler = new Handler();
final InheritableThreadLocal<String> foo = new InheritableThreadLocal<String>();

final Runnable r = new Runnable() {
    public void run() {
         System.out.print(foo.get()); // prints "Bar"

handler.postDelayed(r, 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download