Had a query with synchronization in servlets. Had a requirement of making file accesses through a servlet synchronized. What i can think of making the read/writes in a synchronized block with the lock being the servlet class name. Is that fine and any other ways?
or you should be able to use 'this' for synchronized block. But i would suggest, dont write synchronized blocks, instead make your servlet stateless.
sudhir nim wrote:You can use singleThreadModal, or just don't have any class level variables in your servlet and you wouldn't need to synchronize. or you should be able to use 'this' for synchronized block. But i would suggest, dont write synchronized blocks, instead make your servlet stateless.
There are multiple problems with these bits of advice.
Firstly, don't use SingleThreadModel, ever. It does not guarantee thread safety, and completely kills concurrency.
Secondly, not having class level variables by itself does not guarantee thread-safety, either, and is actually not even required if you know what you're doing.
Thirdly, there's nothing wrong with using synchronized blocks as such. Just don't put the entire code in one because that kills concurrency.
Lastly, I'm not quite sure what you mean by "stateless" servlets, but assuming you mean no class variables - see #2.
To answer the question: synchronizing on the servlet class is fine. Since servlets are generally instantiated once, it amounts to the same as synchronizing on "this", but using the class makes sure the right thing happens.
And finally: If you're serious about multi-threaded code -and these days, who can afford not to be? web apps *are* multi-threaded- I strongly advise to work through one of the eminent books on Java concurrency (either Oaks/Wong or Goetz et al.). There are a *lot* more options than this post mentions and you really need to understand what's available to write effective and efficient concurrent code.
I keep hearing that dont ever use scriptlets, dont ever use expressions, and SingleThreadModal, why guyz at sun just dont remove it and lighten the burden on the guyz who provide implementations if all of these things are never supposed to be used.
But I agree with your view on not using SingleThreadModal though, and after reading again, 'no class variables' wouldn't be sufficient here.
When all this was being worked out, the designers were working in totally new territory so it is not surprising that some ideas turned out not as useful as expected.