aspose file tools*
The moose likes Servlets and the fly likes Making Servlet Thread Safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Making Servlet Thread Safe" Watch "Making Servlet Thread Safe" New topic
Author

Making Servlet Thread Safe

Mohammad Sufiyan Al Yousufi
Greenhorn

Joined: Aug 30, 2010
Posts: 11
Hi Friends,

I have one doubt. Here is simple code which is a servlet.



As to make this code thread safe, do we need to make the increamentValue() method synchronized or do we need to use a Synchronized block in doPost() method. I believe that making increamentValue() method as synchronized will not make it thread safe. We have to use Synchronized block in doPost() method. Please let me know i am correct or not.

In a book, it is saying the below code is Thread safe but I think it is not thread safe. Please correct me.



I just want to say, making the incrementValue() method synchronized is not enough to make it thread safe.

Regards,
M.Sufiyan
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

it is thread safe, since only one thread is able to alter the value of the shared state (ie the 'x' instance variable).
It just isn't a very good way to achieve thread safety.
Mohammad Sufiyan Al Yousufi
Greenhorn

Joined: Aug 30, 2010
Posts: 11
David O'Meara wrote:it is thread safe, since only one thread is able to alter the value of the shared state (ie the 'x' instance variable).
It just isn't a very good way to achieve thread safety.


I think, it seems thread safe but it is not. I may be wrong.. Lets say, two thread accessing the below code..



Thread-1 while executing the increamentValue() method, which will be sequential. After making changes to x variable. And while Thread-1 executing Line B, it may happen that Thread-2 executes the incrementValue() method and While Thread-1 executing Line C, it gets wrong output. This is the only doubt I have, to make this program thread safe, I think, we should use Synchronized block in code like..



Am I correct?
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30913
    
158

The code is thread safe because thread safety refers to state. In particular, the state of variable x. Printing out an old value isn't part of thread safety. It also has less meaning. By the time the response streams back to the browser, it could be out of date anyway.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
 
 
subject: Making Servlet Thread Safe