Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

making instance variables thread safe...

 
ajay vasudevan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the SERVLET scenario.
from a doGet method, i set a instance variable which i use in doPost method.i had to make the variable an instance variable.all the transaction does take place in the doPost method.after the transaction , i set the variable to default value i.e "#".

how can i make the variable thread safe in this scenario ?by sychronizing on the servlet class or making the variable VOLATILE ?

please comment on the above case and reply back .

rgds,


ajay vasudevan
scjp 1.4
 
amar verma
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ajay,
Servlets with instance variables are not thread safe,
synchronization or implementing singlethreadmodel interface on servlet, will keep other requests waiting,
resuling in poor performance and in that case there is no use of servlet, because servlets are to handle multiple requests.

see if you can build your logic in such a way that you need only local variable in a method not instance variable.
that will make it thread safe.
may be i can suggest something if u share your code

other inputs pls

thanks
Amar
 
Anand Wadhwani
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ajay,

It's not a good practice to write both doGet and doPost and do different stuff in those two and worse part is to share an instance variable in those two methods.

Anyway as Amar suggested, you could use SingleThreadModel or you could use synzhronized doGet and doPost method or synchronized block on the varible before you do anything with it in all those methods, but then this all are leading to severe performance problems.

I also would like to look at code before giving any fruitful valuable suggestion!

Often servlet instance variables are required when multiple methods inside servlet need to access some common data. Using instance variables for sharing data among multiple methods of a servlet is not a good idea. For this you could pass those data to other methods via method arguments, using StringBuffer, or array or something.
 
ajay vasudevan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx amar and anand.

i did just the same.i dropped the instance variables and made a hidden variable which contained both the emp code and empname and i submitted the page with method = "post".

and in doPost i read the hidden parameter with req.getParameter("hid_variable") and the problem was solved.

so i got the variables in local variables.


rgds,

ajay vasudevan
scjp 1.4
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic