This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making Servlet Thread Safe

 
Mohammad Sufiyan Al Yousufi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34686
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic