FlickrJ’s ThreadLocal gotcha

If you use Desktop license from Flickr, you have to use the RequestContext class as follows from the FlickrJ examples:

Auth token = this.flickr.getAuthInterface().getToken(frob);
RequestContext.getRequestContext().setAuth(token);

RequestContext stores the token in a ThreadLocal variable. To be brief, I’m running an app on Tomcat. Tomcat uses a ThreadPool. RequestContext corrupts my app because the threads go back to a pool, they don’t die. So, the token of previous users show up in new user’s requests. Not good, and took a while to track down this bug.

I’ve added checks in my FlickrDAO class to clear out the RequestContext’s threadlocal variables at the beginning of each public method that can be impacted. Now my users authenticate properly with Flickr, and information doesn’t leak between requests.

This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to FlickrJ’s ThreadLocal gotcha

  1. Daxon says:

    I read about the lack of thread safety with Flikrj. How did you clear the RequestContext at the beginning of each method?

    Another thing with Flickrj in a web app it seems like you have to call for a frob before the user can authenticate, (This are not recommended for web apps)

  2. Ed says:

    Hi Daxon,

    Here’s how I solved the threadlocal issue in my app.

    /**
    * FlickrJ has a bug when run using a threadpool (like Tomcat uses)
    * Calling this method before creating a new Flickr client keeps stale data
    * from corrupting FlickrJ calls.
    * This is due to poor use of ThreadLocal by FlickrJ library.
    */
    private void threadlocalWorkaround(){
    RequestContext.getRequestContext().setAuth(null);
    }

  3. Ed says:

    I have been using desktop authentication with my webapp, but that has become particularly unattractive recently. Flickr has now added new warnings to the user about the mismatch. I’ll be looking into switching to the correct auth style. (though it was nice to have desktop authentication for running my functional tests on Hudson.)

Leave a Reply

Your email address will not be published. Required fields are marked *