threadlocal variables in a servlet - java

Are the threadlocals variables global to all the requests made to the servlet that owns the variables?
I am using resin for the server.
Thanks for awnser.
I think I can make my self more clear.
The specific Case:
I want to:
initialize a static variable when the request starts the execution.
be able to query the value of the variable in the further executions of methods called from the servlet in a thread safety way until the request ends the execution

Short answer: Yes.
A bit longer one: This is how Spring does its magic. See RequestContextHolder (via DocJar).
Caution is needed though - you have to know when to invalidate the ThreadLocal, how to defer to other threads and how (not) to get tangled with a non-threadlocal context.
Or you could just use Spring...

I think they are global to all requests made with that specific thread only. Other threads get other copies of the thread-local data. This is the key point of thread-local storage:
http://en.wikipedia.org/wiki/Thread-local_storage#Java.
Unless you check the appropriate option in the servlets config, the servlet container will use your servlet with multiple threads to handle requests in parallel. So effectively you would have separate data for each thread that's up serving clients.
If your WebApplication isn't distributed (runs on multiple Java Virtual Machines), you can use the ServletContext object to store shared data across requests and threads (be sure to do proper locking then).

Like Adiel says, the proper way to do this is probably to use the request context (i.e. HttpServletRequest), not to create a ThreadLocal. While it's certainly possible to use a ThreadLocal here, you have to be careful to clean up your thread if you do that, since otherwise the next request that gets the thread will see the value associated with the previous request. (When the first request is done with the thread, the thread will go back into the pool and so the next request will see it.) No reason to have to manage that kind of thing when the request context exists for precisely this purpose.

Using ThreadLocal to store request scoped information has the potential to break if you use Servlet 3.0 Suspendable requests (or Jetty Continuations)
Using those API's multiple threads process a single request.

Threadlocal variables are always defined to be accessed globally, since the point is to transparently pass information around a system that can be accessed anywhere. The value of the variable is bound to the thread on which it is set, so even though the variable is global, it can have different values depending on the thread from which it is accessed.
A simple example would be to assign a user identity string to a thread in a thread local variable when the request is received in the servlet. Anywhere along the processing chain of that request (assuming it is on the same thread in the same VM), the identity can be retrieved by accessing this global variable. It would also be important to remove this value when the request is processed, since the thread will be put back in a thread pool.

Related

Is there any way to pass value from from servlet to calling business methods without sending it as parameter

I have a Servlet which calls some business methods and have a requirement to generate a unique transaction id for each and every request this servlet process and we need to pass this transaction id to the business methods.
One solution would be passing this transaction id as a parameter to all the business methods. But this is not a good solution as the code is redundant and unnecessary.
You could add it as a thread local variable in the servlet and access it for anywhere else. Each incoming request would spawn a new thread and thread local variable would be local to that thread alone
I have solved this by use of ThreadLocal.
Thread Local can be considered as a scope of access, like a request scope or session scope. It’s a thread scope. You can set any object in Thread Local and this object will be global and local to the specific thread which is accessing this object. I have referred this article to fix this.

Threadlocal for initialise a variable in java web project

I want to intialise a variable for a HttpServletRequest. for that i want to check if the request have already intialise the variable or not. am using tomcat server
for example:
A HttpServletRequest has so much DBoperations to be performed. so can i use one connection for the entire HttpServletRequest. also allocate different connections for different request. can i perform this by using Threadlocal ?
Yes, you can do that. Java web servers like Tomcat or Jetty are thread pooled servers, which means each HttpServletRequest is handled by a thread from the server thread pool.
When working with database connections, there are two common patterns being applied: connection-per-operation and connection-per-request/thread. The latter is prefered and recommended, and ThreadLocal is used to implement, each thread owns a connection to perform a series of operations.
In fact, framework like Hibernate use ThreadLocal (ThreadLocalSessionContext) to implement connection/session-per-request/thread.
You can read more from here http://www.ibm.com/developerworks/library/j-threads3/.
Update:
You just create a connection and store it in a shared ThreadLocal object, then you get the connection (not shared with other threads) from this to use for all operations within a thread/request as in 'Listing 3" from the link above.
Hope this helps!

Thread safety in java web application?

What does someone mean when I am asked that whether my web application is thread safe or not , considering that I have not used Multiple threads in my webapplication.
In a normal web-application Servlet treats as Singleton class, it means if you are using instance variable in Servlet that is not thread safe in that case it will create an issue for multiple request that is served simultaneously.
A Java servlet container / web server is typically multithreaded. That means, that multiple requests to the same servlet may be executed at the same time. Therefore, you need to take concurrency into consideration when you implement your servlet.
Read more...
What does someone mean when I am asked that whether my web application is thread safe or not
You have to make sure that all the Servlet/JSP are thread-safe. Do it for all server side classes that is treated as Singleton.
I have not used Multiple threads in my webapplication.
Container/web server starts a new thread for each request.
The servlet specification requires a web application to be thread safe, because the servlet container may (and usually does) process requests concurrently. That is, even if you do not start any threads of your own, the servlet container will, and you must ensure your code is still correct in that case.
That involves protecting any objects shared by several threads (such as the contents of the HttpSession, or any singleton objects) from concurrent access.
An excellent answer to a similar question is witten by BalusC here. Also have a look at Tomasz's answer
Generally, instance variables or state can be shared across threads (threads created by application or the container). So any class(object) that exposes its state for modification, can be considered unsafe. So if your service layer calls some data access object method and the dao is an instance variable inside the service class, the question to ask is this - can this dao or the state of that dao itself be changed by some other client?
You can make your objects immutable. Your custom objects, dates and collections can be mutable. Some of the examples where even getter methods can be dangerous are collections, dates, etc. Use something like ConcurrentHashMap or return a list something like Collections.unmodifiablelist
Another example, instead of returning this.someDate, you should write
public Date getSomeDate() {
return new Date(someDate.getTime());
}
This way some other thread (which may have been spawned by container for another request from another user) holding a reference to the variable someDate will not be able to mess up with this thread.
If you cannot make the state of an object immutable because you want to allow its clients to change its state, you can make all the clients of that object agree to share the state. So if one thread changes the state of a shared object and another thread is ok with the state changed by the first thread, then such monostate object can be ok to have in your application.
As other answers have mentioned the container spawns threads even if your application does not. I have focused here mainly on the topics not directly covered in the answers here so as to avoid duplication. Hope this helps.

Does a session-scoped backing bean have to be implemented thread-safe?

Is it possible, that a session-scoped backing bean is accessed by multiple threads at the same time?
The servlet spec says, it is possible:
Multiple servlets executing request threads may have active access to the same
session object at the same time. The container must ensure that manipulation of
internal data structures representing the session attributes is performed in a thread
safe manner. The Developer has the responsibility for thread safe access to the
attribute objects themselves. This will protect the attribute collection inside the
HttpSession object from concurrent access, eliminating the opportunity for an
application to cause that collection to become corrupted.
However I could not make the server (JBoss) use different threads for the same session. When I opened multiple tabs and started a long running request in one tab, and then started a request in another tab, the second tab had to wait for a response until the action started in the first tab was completed.
I also verified this by blocking the thread with a breakpoint in the backing bean. It was not possible to do anything in other tabs of the same session until I resumed the thread.
Despite this we have some strange exceptions in the production log and so far the only possible explanation we have is, that multiple threads concurrently access the same session-scoped backing bean.
Yes, A Servlet session is thread safe. But, if you are putting mutable object in the session. The application should take care of the synchronization.
In your case, if your Bean is Mutable i.e, has state. Yes it has to be thread safe.
And about your test case, it depends on the browser you are using. Most browsers support upto 6 connections in parallel for every server. But, Not sure if they use parallel connections if there have cookies.

How the servlets are shared among every request

How the servlets are shared among every request? I understand that each httprequest are allocated to different thread. How about concurrent request?
When you create your servlet you decide whether you will make it single threaded or multi-threaded. You can mark your servlet as single-threaded by implementing the interface
javax.servlet.SingleThreadModel
See this
A single threaded servlet can serve only one request at a time, and that's usually not what we want. So typically we allow our servlets to be multi-threaded and implement accordingly. Code on the assumption that many threads, each of which corresponds to one user's request, may be in our servlet at the same time. This is not hard to do - avoid using instance variables that can be changed by any one request thread and remember that any synchronized code will become a point of contention.
When a Servlet is requested for the first time or when the webapp starts up, the servlet container will create an instance of it and keep it in memory during webapp's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern.
A separate thread is created to handle each HttpServlet Request.
See Servlet Tag Info for details.The info has links to great resources that would give you a better understanding of servlets.
I understand that each httprequest are allocat[ed] to different thread.
Correct.
How about concurrent request?
They are allocated to different threads.

Categories

Resources