advertise

Use the request as a key in a ThreadLocal map

Anthony Eden writes in All Things: ThreadLocal and thread pooling

Now apply this to servlets. You can have one request which sets the thread local object’s state. If the first request completes and the thread local state is not cleared then another request may be able to access the thread local object with it’s state intact.

My suggestet fix is to store a map in the ThreadLocal and use the request as the key to get the actual data. Even if one Thread works on multiple requests, they are protected from eachother because each request has no reference to another request:

class RequestThreadLocalHelper {
  private static ThreadLocal data = new ThreadLocal();

  public RequestThreadLocalHelper {
    data.put(new HashMap()));
  }

  public void put(Request request, Object value) {
    ((Map) data.get()).put(request, value);
  }

  public Object get(Request request) {
    return  ((Map) data.get()).get(request);
  }
}

{ Comments are closed! }

mail conditions
Bear
partner