0

In my code I do different HTTP requests in different threads at the same time. I noted that each thread write/read in the same Cookie manager mixing the cookies resulting in strange behaviours (for example, logging in with some credentials in one thread I see the same user information in other threads).

I tried a thread indipendent solution using this CookieStore implementation:

public class ThreadLocalCookieStore implements CookieStore {

private final static ThreadLocal<CookieStore> ms_cookieJars = new ThreadLocal<CookieStore>() {
    @Override
    protected synchronized CookieStore initialValue() {
        return (new CookieManager()).getCookieStore(); /* InMemoryCookieStore */
    }
};

public void add(URI uri, HttpCookie cookie) {
    ms_cookieJars.get().add(uri, cookie);
}

public List<HttpCookie> get(URI uri) {
    return ms_cookieJars.get().get(uri);
}

@Override
public List<HttpCookie> getCookies() {
    return ms_cookieJars.get().getCookies();
}

@Override
public List<URI> getURIs() {
    return ms_cookieJars.get().getURIs();
}

@Override
public boolean remove(URI uri, HttpCookie cookie) {
    return ms_cookieJars.get().remove(uri, cookie);
}

@Override
public boolean removeAll() {
    return ms_cookieJars.get().removeAll();
}
}

Then I call this before any of the thread starts

CookieHandler.setDefault(new CookieManager(new ThreadLocalCookieStore(), CookiePolicy.ACCEPT_ALL));

But nothing changed, I see cookies from one thread mixing with other threads cookies.

How can I solve this? Where am I doing wrong?

Federico Mastrini
  • 724
  • 11
  • 15

0 Answers0