aishwarya lakshmi wrote:i got this question when in an interview..
The exact question is
1) can we create synchronized block of code inside service method to protect that block of code shared by multiple thread.
The answer is yes:
Joined: Jun 29, 2008
Technically it can be done, but logically wrong.
If you use a vector, anyhow it is synchronized and it should do no damage. Also depends on how you are implementing.
Joined: Aug 13, 2007
Yes,Aneesh is right . Vector is already threadsafe , so we dont need to take care for that.
and use synchronized clock only for critical code like bank application withdraw & deposit method.
Author and all-around good cowpoke
Joined: Mar 22, 2000
I agree with Bear - the question is seriously flawed.
1. ANY number of Threads can be executing the same block of code "at the same time" without a problem. It is the variables that you have to think about, not the code. This is true in any language, not just Java.
2. ONLY the request Thread which calls service can modify the request and response variables - no other request Thread can see them.
3. ONLY the request Thread can modify variables created and reference locally inside the service method. NOTE the important word "locally" - if the only reference to an object exists in the stack of the calling Thread, it is completely isolated.