File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Servlets mutlithreading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlets mutlithreading" Watch "Servlets mutlithreading" New topic

Servlets mutlithreading

Gina vernon
Ranch Hand

Joined: Jan 16, 2009
Posts: 108
I have looked through the documentation and have found 2 methods for multithreading servlet methods, (1)synchronizing (2)singlethreadmodel. (1) could cause deadlocking and congestion, (2) has been deprecated as of 2.4. Are there other approaches?
Bauke Scholtz
Ranch Hand

Joined: Oct 08, 2006
Posts: 2458
Certainly. Just write good code. Keep in mind that there is only one instance of the servlet in application's lifetime which is to be (re)used among all requests. So whenever you use instance variables, then those won't be threadsafe. But if you use method local variables, those will be threadsafe. Whether threadsafety has impact depends on the variable in question. If the variable is intented to hold request or session scoped values (e.g. request parameters, logged in user, etc), just declare them in method block. If the variable is intented to hold application scoped values (e.g. the DAO class, some constants, etc), then you can safely declare it as instance variable.

There's absolutely no need for synchronizing or SingleThreadModel if you write correct code (that's also one of the reasons why SingleThreadModel is deprecated).
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63865

What's the need? It's usually sufficient to ensure that your servlets are written in a thread-safe manner.

I've never had to really upon any multi-threading except for that already provided by the container. If you express what you're trying to accomplish perhaps a solution could be ventured?

[Asking smart questions] [About Bear] [Books by Bear]
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
The best approach?

Thoroughly understand what the servlet container provides for you.

Always keep in mind that servlets work on a request/response basis.

Remember there is only one instance of a servlet potentially working on multiple requests "at one time" so pay attention to the scope of variables.

Gina vernon
Ranch Hand

Joined: Jan 16, 2009
Posts: 108
I will work on that. Thanks all.
I agree. Here's the link:
subject: Servlets mutlithreading
It's not a secret anymore!