开发者

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 in开发者_如何学Goserts 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜