java : if i create new object on each request do i need threads still?
general question it can be in c i guess also
if i have ( in my case http requst class ) that invoked from wrapper function this wrapper function is public API . then inside the wrapper function i init new Request object that suppose to do request with the parameters coming from the wrapper function do i need to wrap the request object in thread ( i have thread pool class that execute worker threads ) does creating object on the stack for each request will do ? for example:public void Wrapper(String a,String b)
{
// im doing ..
MyRequst req = new MyRequest(a,b); // will do the http requst
}
or to do :
public void Wrapper(String a,String b)
{
// im doing ..
MyThreadPool.GetInstance().RunTask(n开发者_如何学JAVAew MyRequest(a,b)); // will do the http request
}
The question isn't very clear, but from what can be inferred, the pertinent question is whether creating local variables is sufficient for thread-safety. The answer is yes.
From Java Concurrency in Practice:
Accessing shared, mutable data requires using synchronization;one way to avoid this requirement is to not share. If data is only accessed from a single thread, no synchronization is needed.
It should be remembered that all objects are stored on the heap. The items on the stack are primitives and references to objects on the heap, and are termed as local variables and are always one-word wide (except for long and double values); these variables are not to be confused with the concept of method-local variables in the Java programming language (which people incorrectly assume to be stored on the stack).
By using local variables, one ensures that the objects on the heap are accessible only to the current thread of execution, unless of course, any attempt was made to share such objects with other threads (in which case appropriate synchronization techniques needs to be employed).
This gives an alternative to what you might be trying to do. I am assuming you are trying to manipulate the request object. Have you considered using "HttpServletRequestWrapper".
http://download.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletRequestWrapper.html
Check this link: http://www.oracle.com/technetwork/java/filters-137243.html In the above webpage goto the section which says "Programming Customized Requests and Responses".
Another example, http://www.coderanch.com/t/172274/java-Web-Component-SCWCD/certification/When-HttpRequestWrapper
精彩评论