my dog learned polymorphism*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes question on thread safety and attributes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "question on thread safety and attributes" Watch "question on thread safety and attributes" New topic

question on thread safety and attributes

Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
Consider the following servlet code:

Which of the variables used in the above servlet reference objects that are thread safe? (Select two)
a req
b res
c session
d ctx
Answers: a and b

but i choose c,d.the reason why i choose c,d is -
"if we look at the 'session' and 'ctx' attributes from the perspective that they are local java objects ( for the time forgettting that they are HttpSession and ServletContext respectively ), then they seem to be thread safe."

but the author ( Hanumant Deshmukh page 441 - 442 ) says -

"Request and response objects are accessible only for the lifetime of a request, and so they are thread safe. Session and context objects can be accessed from multiple threads while processing multiple requests, which means they are not thread safe."

but he over looks that 'session' and 'ctx' are local and thus (seem to be) thread safe. !!

please help
thanks in advance !

SCJP 1.4 - 95% [ My Story ] - SCWCD 1.4 - 91% [ My Story ]
Performance is a compulsion, not a option, if my existence is to be justified.
Deepak Bala

Joined: Feb 24, 2006
Posts: 6661

huh !? who ever heard of access specifiers inside methods ?

I think those should be outside of the doGet() method. Also, even if they are private references (and you assign the session and context to them from doGet), you can get the session and context from another servlet in the same way. So that makes them not thread safe.

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
hmm....!!! john..!!! thanks a lot.
i never looked to the case that the local variables are declared private.
so even if the are declared out of doGet( )they become instance variables and thus arent thread safe !!

so the question is a bit wrong as the local variables are declared private
but neglecting that, the arguements to the method, i.e request and response are thread safe !
It is sorta covered in the JavaRanch Style Guide.
subject: question on thread safety and attributes
Similar Threads
Question On Thread Safety
Regarding SingleThreadModel from J@Whiz
I know local objects are thread safe. But why not obj here too?
manning's question about thread safe
question from JWebplus1.4 about session.invalidate()