dcsimg
Servlets and Thread Safety
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Steve_Long
Posted On:   Saturday, May 18, 2002 07:31 AM

Is the following thread safe, where a servlet instantiates a class and that class instantiates another class, ie Servlet -> new ClassX() -> new ClassY() -> new ClassZ()           -> new ClassX() -> new ClassY() -> new ClassZ() ? ---------------------------- public class MyServlet extends HttpServlet { ... ...// init stuff ... protected void doGet( HttpServletRequest q, HttpServletResponse r ) throws ServletException, java.io.IOException { processRequest( q, r ); } protected void doPost( HttpServletRequest q, HttpServletResponse r ) throws ServletException, java.io.IO   More>>

Is the following thread safe, where a servlet instantiates a class and that class instantiates another class, ie


Servlet -> new ClassX() -> new ClassY() -> new ClassZ()

          -> new ClassX() -> new ClassY() -> new ClassZ()


?


----------------------------


			
public class MyServlet extends HttpServlet {
...
...// init stuff
...
protected void doGet(
HttpServletRequest q, HttpServletResponse r )
throws ServletException, java.io.IOException
{
processRequest( q, r );
}

protected void doPost(
HttpServletRequest q, HttpServletResponse r )
throws ServletException, java.io.IOException
{
processRequest( q, r );
}

private void processRequest(
HttpServletRequest q, HttpServletResponse r )
throws ServletException, java.io.IOException
{
(new MyBean()).run( q, r );
}
}

public class MyBean extends Object {

public MyBean() {}

public void run(
HttpServletRequest q, HttpServletResponse r )
{
...
... // figure out which other bean to use
...
Class[] parms = new Class[] {
HttpServletRequest.class,
HttpServletResponse.class };

Object[] args = new Object[] { q, r };

try {
Class bean = Class.forName( someBeanName );
Object object = bean .getConstructor(null)
.newInstance(null);
Method method = bean.getMethod( "run", parms );
method.invoke( object, args );
}
catch (Exception e) {}
}
   <<Less

Re: Servlets and Thread Safety

Posted By:   Lunkwill_Vroomfondel  
Posted On:   Sunday, May 19, 2002 10:02 AM

your abstract description doesnt include any thread-risks at all:

new ClassX() -> new ClassY() -> new ClassZ()

since there arent any shared ressources.



in your sample-code you seem to share the http-request and http-response between two objects (the http-servlet itself and MyBean).

but i dont see any operations on the shared objects, so yes, it is perfectly thread-safe from my point of view... ;-)



you would have to put in more code, because there are also some tripwires arising from the internal functioming of the http-servlet-streams. e.g. you must not try to write to a http-servlet-stream after having read from the counterpart!



hope, it helped at least a bit.
About | Sitemap | Contact