wood burning stoves
The moose likes Servlets and the fly likes thread safe servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "thread safe servlet" Watch "thread safe servlet" New topic

thread safe servlet

shivdhwaj pandey
Ranch Hand

Joined: Nov 12, 2011
Posts: 67

what is thread safe servlet?

with regards,
Shivdhway Pandey
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

A servlet that can handle requests from multiple threads concurrently without its internal state (or that of the request, response, session, etc; attributes really need to be looked at carefully) getting in an inconsistent state.

How To Ask Questions How To Answer Questions
shivdhwaj pandey
Ranch Hand

Joined: Nov 12, 2011
Posts: 67

Rob Spoor thanks but can you please explain it more
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
You can search for it. It basically means your code should be able to handle multiple concurrent requests without any issues. One thing that will help is to not use instance variables.

So much trouble in the world -- Bob Marley
Pene charl

Joined: Jun 14, 2011
Posts: 21

A servlet can handle concurrent requests in a same time.That situation one can modify the instance data while other person has to work on that same inside service().Here deadlock could be occured.so,we need to avoid that situation with the help of thread safe (i.e synchronized keyword).

Regards:Prince Charles
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63838

The synchronized keyword should be avoided unless absolutely necessary. There are better ways to make servlets thread safe. Not using instance variables for example. In over a dozen years of writing servlets, I've never had to use synchronized even once.

[Asking smart questions] [About Bear] [Books by Bear]
Kumaravadivel Subramani
Ranch Hand

Joined: Jul 05, 2008
Posts: 171

I go with Bibeault word, I've never used synchronized in methods or in blocks. Used instance variables and as already explained here got overwriting problem between requests on instance variables. Now changed all instance variables into inner class and initiating this class for all requests, by this can be avoided the situation of overwriting and synchronization.

No pain, No gain.
OCJP 1.6, Liferay Certified Developer 6.1
Tim Moores

Joined: Sep 21, 2011
Posts: 2413
While one shouldn't synchronize entire methods, I see no reason to try and avoid the synchronized keyword entirely for code blocks. Sometimes that is the best way to ensure thread safety, for varying definitions of "best". In order to make an informed decision what the best approach is I recommend to work through one of the eminent books on Java concurrency, either Java Threads by Oaks/Wong or Concurrency in Practice by Goetz et al.
I agree. Here's the link: http://aspose.com/file-tools
subject: thread safe servlet
It's not a secret anymore!