JavaBeat Certifications Certifications Kits Articles Interview Questions OCAJP 7 OCPJP 5 OCPJP 6 OCEJWCD 6 SCBCD 5.0 SCEA SCJA

What is a better approch for enabling thread safe servlets ?

Topic :
Feedback Request New QnA Print Email

There are two apparent options to make a servlet threadsafe.
1) Synchronizing doXXX() method
2) make the servlet implement SingleThreadModel

But there are pros and cons in both.

Synchronizing doXXX() method

In this case, while one request is being processed by servlet, any other request will have to wait for the completion as the running thread will occupy the lock to the servelt object. This severely hits performance and servlet looses its key feature of concurrency.

make the servlet implement SingleThreadModel

If your servlet implements SingleThreadModel, an instance of the servlet will be created for each request that comes in for the servlet thus ensuring that same instance of servlet should not be accessed for parallerlly running threads. This does not hamper concurrency but may defeat sole purpose of sychronization. For Example: if the servlet is having static variables and the threads are modifying those variables, then SingleThreadModel will not work. Same is the case with Context and Session scoped variables.

So the best solution of implementing thread safety in servlets is to use Synchronized (Object o ){} blocks and implement thread safety on object to object basis as required.

Topic :
Feedback Request New QnA Print Email

All api java java 6.0 java 7.0 jdbc jsp servlet ejb jndi jms ejb 3.0 j2ee jee 5.0 jee 6.0 jsf struts spring Hibernate ajax JBoss Seam netbeans eclipse ant xml maven dojo junit javafx j2me log4j ESB JBoss Apache Quartz scjp mysql oracle gwt openjpa jmx yui google-guice android JBoss scwcd 5.0 scjp 1.5 scjp 1.6 scja scbcd 5.0

javabeat | advertise | about us | contact | useful resources
Copyright (2004 - 2013), JavaBeat