JBridge

JBridge: Certification Question Of The Day

JBridge Home >> Certification Questions >> Question for Tuesday May 13th 2003 Tuesday May 13th 2003

Examine the following JSP code, then identify which variables and objects are threadsafe: (5 correct answers)

<%! int counterA = 0; %>
<% Integer tempInt = (Integer) session.getAttribute("counterB");
   int counterB = tempInt.intValue(); %>
<% int counterC = 0; %>
<% int counterDD = incrementCounter(0); %>
<%! private int incrementCounter(int counterD) {
	  return counterD ++;
   }
%>
<%! static int counterE = 0; %>


A counterA
B counterB
C counterC
D counterD
E counterDD
F counterE
G tempInt
H The object held as attribute "counterB" by the session.
Page down for the answer...











































The Answer

Answers B, C, D, E and G are correct. counterB, counterC, counterDD and tempInt are local variables within the jsp's service method, while counter D is a method parameter. Both types of variable are thread safe.
counterA (answer A) becomes an instance variable in the jsp service variable, so is shared among all threads sharing the jsp instance.
counterE (answer F) is no more thread safe for being static - infact, less so, as it is shared among all instances of the jsp class.
The object held as attribute "counterB" by the session (answer H) is not thread safe either, though in most circumstances it could be regarded as such. However, it is quite possible to initiate two or more threads from the same session. Of course, this also means that tempInt and counterB - as they take their values from this session attribute - may not be reliable, even though in themselves they are thread safe variables.


EMail: dbridgewater@jbridge.co.uk
Phone: +44 (0)1943 877414
Fax: +44 (0)1943 877414
Mail: David Bridgewater, Willow Dene, Bradford Road, Menston, Ilkley, West Yorkshire, LS29 6ED, UK
Copyright © 2003 David Bridgewater. All rights reserved.