Threadlocal for initialise a variable in java web project - java

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!

Related

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.

Servlet Instance in the container

I knew only one servlet instance (One instance for one servlet basis) will be avilable in the web container. Is it possible to make a pool of instance in the web container ? Like a database connection? If i make a pool of servlet instance then how i can make that as a thread safe? (But i studied we can make only one servlet instance per servlet).
I understand that it was an interview question. I would have answered it as follows:
You can let the servlet implement SingleThreadModel to get the container to create a pool of multiple instances of the same servlet class. The maximum pool size depends on the container used, on Tomcat for example, this is 20. But, a big but, this interface is deprecated since Servlet 2.4! We should actually be writing servlets in a thread-safe manner, without assigning request- and/or session scoped data as an instance variable of the servlet. This way it's safe to use a single servlet instance across multiple threads (read: across multiple HTTP requests).
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
Question is, why would you want to do that?
Servlet container instantiates single instance for each servlet declaration. That means, that you can have multiple servlet instances, but you need to declare the servlet as many times as many instances you want/need. This also brings the question of how servlets would be invoked ... they would need to be mapped to different paths.
Another way you can do this is to make a pool of handlers which your single servlet may call.
Re how to make them thread-safe: that depends on what exactly you want to do in those handlers. It's hard to tell you in general.
If you're asking about thread-safe pool, you can use Apache Commons Pool library, or some BlockingQueue (e.g. LinkedBlockingQueue) in Java: queue may contain your handlers. Servlet will take() first handler, use it, and put() it back after it's done. (This is just an example of course, there are many ways to implement pool).
But ... make sure you really need design like this, maybe your requirements can be satisfied by something simpler? (If your goal is to limit number of concurrent requests handled at the same time, maybe it's enough to just limit number of HTTP worker threads in your container? Or if that's not enough, you can use a limiting filter?)
Defining a pool of servlets does not make sense as the Servlet itself is not a thread. The Web Container (e.g. Tomcat) maintains a thread pool which calls the Servlet instance. So if you want to increase the throughput (concurrent users) you have to increase your web containers' pool size.

How singleton is used to manage database connection?

This may be a very old, many times asked question. But I am not able to find a proper answer to it, so asking again.
For the database connections, we always use a singleton object. When the database is being accessed by thousands of users, how does the performance is maintained? I mean if there are thousands of requests per second, how the database connection is managed since we are using a singleton? Are the database requests serialized? Or a singleton is not used in these cases?
I know it is a kind of dumb question, but I am seriously confused. If anyone can give some reference reading link, it will be nice.
Thanks.
I'm not sure whether you've confused the use of a plain singleton with a service locator. Both of them are design patterns. The service locator pattern is used by applications to ensure that there is a single class entrusted with the responsibility of obtaining and providing access to databases, files, JMS queues, etc.
Most service locators are implemented as singletons, since there is no need for multiple service locators to do the same job. Besides, it is useful to cache information obtained from the first lookup that can be later used by other clients of the service locator.
By the way, the argument about
"it's to ensure that there is always only one active connection to your DB"
is false and misleading. It is quite possible that the connection can be closed/reclaimed if left inactive for quite a long period of time. So caching a connection to the database is frowned upon. There is one deviation from this argument; "re-using" the connection obtained from the connection pool is encouraged as long as you do so with the same context, i.e. within the same HTTP request, or user request (whichever is applicable). This done obviously, from the point of view of performance, since establishing new connections can prove to be an expensive operation.
i recommend to use connection poolinghttp://www.java2s.com/Code/Java/Database-SQL-JDBC/PooledConnectionExample.htm
Even though you haven't put anything about sessions/transactions/ORM, I think your question comes from Hibernate, JPA or other ORM background.
As such, for any transaction to happen, we need an entityManager or session. These sessions could be created for each transaction.
Now by using factory pattern, we can get as many similar objects as we want... But the factory itself should be singleton. So in DB operations, the entityManagerFactory or sessionFactory objects are kept as singletons.
When you think about it, it makes sense because after all a sessionFactory represents a configuration(DB, UserID, password, connection pool size, caching, etc). What you need to perform DB transaction is not the factory but the object(session) created by the factory. These you can have as many as you want. But if you have multiple factories, it just is unnecessary creation of same (similar) objects.
We use connection pooling in plain jdbc as well as ORM.
If your database connection creating singleton is stateless (which it should be, or at least should be immutable), its pretty simple.
When your web application is accessed by thousands of users simultaneously, there are actually thousands of threads, one per user. Each thread has its own Program Counter which keeps track of what instruction thread is currently processing. When a thread would access a public method of your singleton, for example myDBConnectionManager.getConnection(), it would start executing instructions specified within. Therefore, it is a thread that is actually creating a database connection by reading instructions specified in myDBConnectionManager.getConnection() method. The methods of singleton are only manuals that instruct threads what to do.
This way, your application can create millions of connections at the same time with a singleton as long as it is able to create millions of threads simultaneously.

Handling requests using threads

I am writing an application using JSP & Jdbc, Where i have a table name "COMMENT_DATA", In which user can post their comments on that. So now If more than one user is writing comments and posting it at the same time, I am going for threads. So I will be Synchronizing the method which inserts the data onto the Database. Then how to handle the other requests ie., how to queue out the other requests and how to take back and make them write into the Database
Exactly. Each HTTP request is already a thread at its own. Keep in mind that the web container will create only one servlet instance during application's lifetime and that the servlet code is been shared among all requests. This implies that any class-level variables or static variables are going to be shared among all requests. If you have such one variable, it is not threadsafe. You need to declare request-specific variables threadlocal at method-level.
As to JDBC: just write solid code and everything should go well. Using a connection pool is only useful to improve connecting performance (which is really worth the effort, believe me, connecting the DB is a fairly expensive task which may account up to at least 200ms or even more, while reusing a connection from the pool costs almost nothing). It only doesn't change anything to the threadsafety of the code you write, it's still in your control/hands. To get a clear picture of how to do the basic JDBC coding the right way, you may find this article useful.
As above the servlet container will handle the threading of the requests for you. I.e. for each different user than connects to the server a new thread will be created with out you knowing.
So all you have to do is ensure your jdbc code is thread safe and you should be fine. The database will do all of the necessary locking for you :-)
Karl
I'm not sure why you need to worry about this. The servlet container will handle the threading (say, via a threadpool). The database will handle multiple connections, so if you're not modifying shared state across different threads in the application, you shouldn't have to worry about this.

threadlocal variables in a servlet

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.

Categories

Resources