Reputation: 4568
I have this code running in a servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) {
final HttpServletRequest requestF = request;
Runnable runner = new Runnable() {
public void run() {
String something = requestF.getParameter("anything");
//do other things...
}
};
Thread thread = new Thread(runner);
thread.start();
But it throws an Exception when i try to get the parameter from the request object.
Exception in thread "Thread-25" java.lang.NullPointerException
at org.apache.catalina.connector.Request.parseParameters(Request.java:2560)
at org.apache.catalina.connector.Request.getParameter(Request.java:1086)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:355)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
at br.com.test.controller.ajax.MyServlet$1.run(MyServlet.java:54)
at java.lang.Thread.run(Thread.java:619)
The requestF
object is not null, I've checked.
Does anyone know if i can access the request object inside a new Thread
?
Upvotes: 4
Views: 3828
Reputation: 131
Yes, Zaske is right. You may copy using a new instance of map object, like this:
final Map<String,String> mapParameters = new HashMap<String,String>();
mapParameters.putAll(request.getParameterMap());
and use mapParameters inside your "run" method:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
final Map<String,String> mapParameters = new HashMap<String,String>();
mapParameters.putAll(request.getParameterMap());
Runnable runner = new Runnable() {
public void run() {
String something = mapParameters.get("anything");
//do other things...
}
};
Thread thread = new Thread(runner);
thread.start();
}
Upvotes: 2
Reputation: 4137
Indeed , the Request is not null.
What I suspect that happened is that since you have a reference to the request object, the GC did not collect it.
However, some cleanup code on the parameters (i.e - removing all entries of the request params) was executed, after the response was handled.
I guess this could have happened in order to release memory resources, and not wait for GC, and this is why you're facing this null pointer exception, which is not due to null access to the request object, but to one of the parameters
I would advise you to get the parameters collection, copy it to a new data structure (i.e - a map) and pass it to your thread.
In addtion, you should think if you want your thread to run prior to the response getting sent to the client, but this is purely a design question.
Upvotes: 5