I have a java appengine app with true. I know that multiple threads will be running on a single instance handling multiple concurrent requests. I understand that the code must be threadsafe, i.e. no global static variables.
What I don’t understand is whether the thread is killed when the request is over, or whether the same thread can be used to process another incoming request once its done processing one.
Why does this matter? Some details:
I have a static class with a thread local variable as such:
public abstract class Foo {
private static final ThreadLocal<Boolean> threadIsApiCall = new ThreadLocal<Boolean>();
static {
setIsApiCall(false);
}
}
This variable stores whether the current request for this thread is a call to our rest api or whether its a call from our own custom client. This variable only gets set if a filter matching our api paths runs. The issue I’m running into is that if a request is made to our API, and the threadlocal variable gets set to true, on subsequent requests (that arent api requests) the threadlocal variable is still set to true. You would suspect that it would be set to false because of the static initializer. The only way it could be set to true still is if the initializer doesn’t run which leads me to believe threads are reused. Is this true?
Thread reuse is an implementation detail of the servlet implementation. Threads are normally reused via thread pool. This can typically be configured via a servlet configuration. Unfortunately this is not the case with GAE.
You can simply check if GAE recycles threads by logging
Thread.currentThread().getName().Because of the possible thread reuse, use of
ThreadLocalin servlets was always a bad idea. UseservletRequest.setAttribute(..)if you need to store some data in request-scope.