Thread safe servlets

I have a question regarding the semantice of servlets. Consider you are calling a method
public StringmodifyAddress(){......}in the service method of the servlet. Now considering that a servlet could be sericing multiple requests would this method be technically thread safe? If not what could we do to make it safe.
cheers

Ok let me rephrase and provide a little more details. Sorry I messed up the question the first time
private String email;
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
   User user = new User;
   String address =  user.modifyAddress(email);
}Now in the class User
public String modifyAddress(String email)
  //writes the email address to a database
}Now I feel since user is a variable local to the service method it is thread safe, but a coworker feels that since email is a member variable it would not be thread safe. Please advise it seems that he might be correct.

Similar Messages

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

  • Thread Safe Issue with Servlet

    I saw the following statement in one of the J2EE compliant server documentations:
    "By default, servlets are not thread-safe. The methods in a single servlet instance are usually executed numerous times simultaneously (up to the available memory limit)."
    I'm quite concerned with this statement for the primary reason that (I'm trying to reason by reading it out loud) servlets are not going to be thread-safe especially when available memory hit really really low!! So, when the application is still having sufficient memory, we will not likely run into concurrency problems, i.e the happy scenario for a short period after server is started. BUT, good things don't last long.. Anyway, hope someone can explain to me with more insights. Thanks.

    Don't worry, memory occupation and thread safety are not related at all.
    In my opinion, the following is the meaning of the statement you quote.
    Since the servlet specification doesn't force any implementation to spawn a new servlet object upon each request (and this should be a real memory hit!), nor to synchronize calls to servlet methods, you should always code your servlet in a "stateless" fashion: you should be aware the same method on the same object could (and probably will) be called concurrently if multiple concurrent client requests are submitted.
    Hope I've been clear enough...

  • Are servlets thread safe??

    Are servlets thread safe?? if not, then how to make them thread safe.

    Hi,
    servlets aren't thread-safe; you can make them thread-safe by implementing the interface javax.servlet.SingleThreadModel
    From the javadoc:
    public interface SingleThreadModel
    Ensures that servlets handle only one request at a time. This interface has no methods.
    If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
    If a servlet implements this interface, the servlet will be thread safe. However, this interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet.

  • Is Servlet thread safe?

    Hi,
    I have created a application. All that the application does is that it listens at a predefined port say 8080 and for every request that is made to the application, the request header information is dumped into a file.
    I have implemented it by creating a servlet that implements the Filter interface and implemented its doFilter() method.
    In the method, I simply make use of the Servlet Request object and wite the header details in a file.
    The question : Is the above written Servlet class - thread safe?
    There are no class member variables defined.
    I have deployed the application on Tomcat 5.0.19.
    Regards,
    Montek Singh Ahluwalia

    Yes, Servlets are thread safe.
    Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the javax.servlet.SingleThreadModel interface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle.

  • Is Persistence context thread safe?  nop

    In my code, i have a servlet , 2 stateless session beans:
    in the servlet, i use jndi to find a stateless bean (A) and invoke a method methodA in A:
    (Stateless bean A):
    @EJB
    StatelessBeanB beanB;
    methodA(obj) {
    beanB.save(obj);
    (Stateless bean B, where container inject a persistence context):
    @PersistenceContext private EntityManager em;
    save(obj) {
    em.persist(obj);
    it is said entity manager is not thread safe, so it should not be an instance variable. But in the code above, the variable "em" is an instance variable of stateless bean B, Does it make sense to put it there using pc annotation? is it then thread safe when it is injected (manager) by container?
    since i think B is a stateless session bean, so each request will share the instance variable of B class which is not a thread safe way.
    So , could you please give me any guide on this problem? make me clear.
    any is appreciated. thank you
    and what if i change stateless bean B to
    (Stateless bean B, where container inject a persistence context):
    @PersistenceUnit private EntityManagerFactory emf;
    save(obj) {
    em = emf.creatEntityManager()
    //begin tran
    em.persist(obj);
    // commit tran
    //close em
    the problem is i have several stateless beans like B, if each one has a emf injected, is there any problem ?

    Hi Jacky,
    An EntityManager object is not thread-safe. However, that's not a problem when accessing an EntityManager from EJB bean instance state. The EJB container guarantees that no more than one thread has access to a particular bean instance at any given time. In the case of stateless session beans, the container uses as many distinct bean instances as there are concurrent requests.
    Storing an EntityManager object in servlet instance state would be a problem, since in the servlet programming model any number of concurrent threads share the same servlet instance.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Thread safe XSLT extension

    We have a servlet that gets called with a set of parameters. I want to set one of those parameters within my XSL extensions so that it is retrievable from the XSL code. Because the extensions are static and used by all XSL transforms, they are not thread safe. Static elements within the class are overwritten by whatever servlet thread last touched it. So my parameter may not be for the thread wanted, but some subsequent thread. How can I get around this without synchronization?

    Would you provide more details of how you define the extensions?

  • HTTP request/response object not thread safe.

    According to the serlvet spec. Http Request/Response
    are not thread safe. Quoting from the Spec:
    " Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread. References to the request and response objects must not be given to objects executing in other threads as the resulting behavior may be nondeterministic."
    This has prompt me to ask the following question.
    For Example I have a servlet which does the following
    request.setAttribute("myVar","Hello");
    The request and response is dispatched(using RequestDispatch.include(request,response)) to another
    servlet which retrieve this attribute i.e request.getAttribute("myVar");
    Is this safe?
    The Spec only said "The Container Provider must ensure that the dispatch of the request to a target
    servlet occurs in the same thread of the same VM as the original request." I take this meaning that the targeting servlet does not have to run in the same thread(only dispatch), otherwise it would be safe.

    To put it another way, you can only have onle thing working on a request at a time. For instance, the ServletContext is available to all servlets running on a server. If you tried to save a particular request to the ServletContext, it would potentially be available to many concurrently running servlets. They could all change whatever in it at the same time. Each servlet is in its own running thread. Hope that helps some.

  • BC4J View not Thread safe, user sessions are using the same view instance

    Hi There,
    We are using BC4J that came with JDeveloper 10.1.2.0.0 with Oracle 10G 10.1.2.0.0.
    I have an BC4J account search view (BC4J AccountSearchView) that users can call to search for an account. So this view could be used by numerous users and pieces of code at the same time. Now my understanding is that each user gets their own instance of the view so changing the view's query should not be an issue (since the view definition is not changing). Under a light load the account search view looks like everyone get there own instance of the view and there expected account search results. But under a heavy user load when we have User A and User B the search query that was for User A will be used by User B. So the user results for one user will get the other users results.
    I do not understand if the view definition is been changed by the other user and is impacting all view instances. How can this occur if it is thread safe?
    I have enclosed the core code for this search.
    If you can help that would be much appreciated, thanks in advance,
    Nigel
    accountSearchView.setQuery(baseSelectQuery+generateWhereClause());
    logger.debug("SearchAccounts Query: "+accountSearchView.getQuery());
    System.out.println("SearchAccounts SQL: "+accountSearchView.getQuery());
    accountSearchView.setPassivationEnabled(false);
    accountSearchView.setForwardOnly(true);
    accountSearchView.executeQuery();
    get attributes for each row result and place in new Java bean objects and return to user.

    Nigel, we've only certified JDeveloper 10.1.2 against the Struts 1.1 with which it ships.
    If there have been any changes in Struts 1.2 to the Struts Request Processor, then this could easily have an impact on the BC4JRequestProcessor's correct functioning, depending on what the changes were.
    My quick look into the issue tells me that the ActionServlet init parameter named mapping in web.xml that we use for the 9.0.3-style BC4J/Struts integration is getting ignored by Struts 1.2. This parameter is used by Struts 1.1 to globally configure a custom ActionMapping subclass which can support additional properties. My quick test shows me that Struts 1.2 is ignoring this setting and so the oracle.jbo.html.struts11.BC4JActionMapping subclass of Struts's default ActionMapping is not getting used correctly as it does in Struts 1.1. This leads to errors when Struts tries to configure its actions in struts-config.xml since the Apache digester tries to set properties on the ActionMapping instance that don't exist (since the BC4JActionMapping has these properties, and it's not being used).
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>mapping</param-name>
          <param-value>oracle.jbo.html.struts11.BC4JActionMapping</param-value>
        </init-param>
      </servlet>This is my quick analysis of what's not out-of-the-box compatible. I don't know enough about the changes in Struts 1.2 to know why this Struts 1.1 feature broke in Struts 1.2, or what the Struts 1.2 way to accomplish the same thing is.
    I'd encourage you to use Worldwide Support's Metalink site and open a TAR for any time-critical issues you need assistance in resolving. Many of us are constantly traveling and only able to sporadically chime in with tips in the forum as our time permits.
    The source of the BC4JRequestProcessor ships with the produce in the ./BC4J/src directory inside the bc4jstrutssrc.zip file.

  • Is this thread safe?

    I've got a HttpServletRequest instance variable in my servlet that I use in my model to retrieve parameters. The servlet looks like:
    public class MyServlet extends HttpServlet implements Controller {
      HttpServletRequest req;
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req = req;
        MyModel model = new MyModel(this);
        model.retrieve();
      public String getParameter(String parameter) {
        return req.getParameter(parameter);
    }The Controller interface has only one method - public String getParameter(String parameter)
    In MyModel because I pass an instance of Controller into the constructor I can do - controller.getParameter(parameter);
    Is what I'm doing thread safe?

    Actually, a static nested class is more appropriate than an inner class as there is no implicit outer-class reference to maintain:
    public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void processRequest(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            MyModel model = new MyModel(new MyController(req));
            model.retrieve();
        private static class MyController implements Controller {
            private HttpServletRequest req;
            MyController(HttpServletRequest req) {
                this.req = req;
            public String getParameter(String parameter) {
                return req.getParameter(parameter);
    }This code is now thread safe because there is a different instance of MyController per thread. Note that if an instance of MyController is accessed by multiple threads, then its thread safety is dependent upon the thread safety of HttpServletRequest. However, based on the sort of thing I assume you are trying to do, I doubt you will be sharing instances between threads.

  • Which is thread safe

    If I implement SingleThreadedModel in a servelt which are all thread safe?
    Request object, response object, instance variables,class variables( by the by can i have class variables in a Servlet ? how/where it will be used?)

    If you use SingleThreadModel, everything will be thread safe, because you are spawning one instance of the servlet, for every request. This WILL NOT scale well if you have many users at once.
    With regard to what is thread safe in a normal servlet, I believe
    request
    response
    session
    variables local to functions
    NOT safe:-
    class variables - these will be shared by multiple instances.

  • Thread safe bean

    My business logic bean is being accessed via jsp's
    It looks something like this
    public class MyBean
    private int myInt;
    private String MySting;
    * Bean sets and gets
    public void setMyInt(int i)
    myInt = i;
    public void setMyString (String s)
    myString = s;
    public int getMyInt()
    return myInt;
    public String getMyString()
    return myString;
    * Public wrapper for private business logic
    public void doSomethingWrapper()
    myString = doSomething(getMyInt())
    * Private business logic
    private String doSomething(int i)
    // business Logic
    return a_string;
    Now, I've been told that this is not thread safe and that will not work. My big concern is
    with making the Bean properties thread safe, anyone way any suggestions? Thanks in advance.

    Based on your requirement, i see a necessicity for session scoping the bean.
    And yes in servlet/jsp multiple thread can act on single instance of a bean.
    So what you do is add synchronized keyword for the getter and setter method. For example if have modify your example given above, it would look something like this
    public class MyBean
    private int myInt;
    private String MySting;
    * Bean sets and gets
    public synchronized void setMyInt(int i)
       myInt = i;
    public synchronized void setMyString (String s)
       myString = s;
    public synchronized int getMyInt()
       return myInt;
    public synchronized String getMyString()
       return myString;
    * Public wrapper for private business logic
    * You dont necessarily have to synchronze this method because
    * getMyInt() is anyway synchronized.
    public void doSomethingWrapper()
       myString = doSomething(getMyInt())
    * Private business logic
    * If you dont access any properties(member variables) dont synchronize, if you do then yes
    private String doSomething(int i)
       // business Logic
       return a_string;
    }By adding synchronized keyword the java virtual machine ensures method level serial execution, so no corruption problem.
    But you require more than method level synchronization, then you need some other mechanism like semaphore and just.
    In most of the case, former would be just enough but if your case is not so then let me know, I can suggest other mechanism which suit your needs

  • Is Oracle JDBC driver thread safe

    Is the Oracle JDBC driver thread safe?

    Seems that this is not totally true.
    We have a Problem with Oracle JDBC driver 9.2.0.5.0 (thin)
    Using an IBM JDK 1.4
    Szenario:
    Thread 1 access to a CLOB via
    ResulSet.getCharacterStream(int)
    Thread 2 normal access via some select and
    ResulSet.getString(int)
    (Both using the same connection)
    The following threads appear to be in a circular deadlock.
    Further information can be found by looking in the Overall Thread Analysis
    section of this tool.
    Multi-threaded deadlock 1:
    "Servlet.Engine.Transports : 6" of (sys:0x39778800) (TID:0x104590D0)
    Holding Resource: oracle.jdbc.ttc7.TTC7Protocol@1ADEB358/1ADEB360
    Thread Waiting: "ProcessNotificationTask" (sys:0x3C51FC18) (TID:0x103B4C40)
    "ProcessNotificationTask" of (sys:0x3C51FC18) (TID:0x103B4C40)
    Holding Resource: oracle.jdbc.driver.OracleConnection@1AE45160/1AE45168
    Thread Waiting: "Servlet.Engine.Transports : 6" (sys:0x39778800) (TID:0x104590D0)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2667)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2840)
    4XESTACKTRACE at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:608)
    4XESTACKTRACE at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:536)
    4XESTACKTRACE at com.top_logic.knowledge.service.db.DBKnowledgeBase.getObjectsByAttribute(Unknown Source)
    4XESTACKTRACE at oracle.jdbc.ttc7.TTC7Protocol.getLobChunkSize(TTC7Protocol.java:3050)
    4XESTACKTRACE at oracle.sql.LobDBAccessImpl.getChunkSize(LobDBAccessImpl.java:687)
    4XESTACKTRACE at oracle.sql.CLOB.getChunkSize(CLOB.java:692)
    4XESTACKTRACE at oracle.sql.CLOB.getBufferSize(CLOB.java:717)
    4XESTACKTRACE at oracle.sql.CLOB.getCharacterStream(CLOB.java:345)
    4XESTACKTRACE at oracle.sql.CLOB.characterStreamValue(CLOB.java:1377)
    4XESTACKTRACE at oracle.jdbc.driver.OracleStatement.getCharacterStreamValue(OracleStatement.java:5817)
    4XESTACKTRACE at oracle.jdbc.driver.OracleResultSetImpl.getCharacterStream(OracleResultSetImpl.java:1230)
    It seems that the access to the CLOB needs another,
    internal SELECT to the Database and this way
    TTC7Protocol and OracleConnection lock out each other.
    This only happens on a true multiprocessor machine.
    We tried to reprodcue it on a Single Processor
    and some HyperThreading Machine but had no real sucess.
    Now where can I sumbit this as a Bug ?

  • Is JSF Page thread safe

    Hi ,
    I was wondering if JSF page is thread safe
    Okay here is my scenarion.
    1. in order to prevent some of the value get re instatiate when the page rendered i declared some of them as static.
    However i make some checking if the Page is accessed for the first time , it will set this static object back to Null , if it is a postback it will hold current value which i assign.
    The question is ,
    1. i have two or three user performing concurrent request will it be a problem ????
    2. i notice when i destroy / invalidate the SessionBean. ( user logout scenario ) .
    When the user login again , why the static variable still holding the same value . i thought the page should be destroyed?? ( Thats why i check if the page is accessed for the first time , i will set all my object to null ).
    Thanks.

    The JSP will we translated to a servet by the application server, and therefore will run as a servlet. Servlets are not thread safe, you'll have to elaborate synchronized code blocks to allow one thread in the critical code, wich in turn has it's drawbacks.
    Best regards
    Antonio.

  • Is the Sun JNDI LDAP provider thread safe?

    Hi,
    The JNDI documentation states that the Context implementation is not required to be thread safe although some providers provide thread safety. My question is whether the Sun JNDI LDAP provider is thread safe or do we have to synchronize on the Context instance?
    Thanks

    Read this: http://java.sun.com/j2se/1.3/docs/api/javax/naming/Context.html
    The answer, I think is no you need to synchronize accesses yourself. If you're using it from a servlet container, this should be OK, since each request is on a separate thread.

Maybe you are looking for

  • Crystal Reports XI - Unable to fetch data error

    Hi all, I get the below error when i click next or previous buton in my report after navigating the report for about 5 to ten minutes. JRCAgent3 detected an exception: Unable to fetch data for the subreport 'Subreport1' at this position. at com.cryst

  • Limiting Outlook 2010 account to send to a single address.

    How can you set up an MS Outlook (2010) account so it can only send to one email address?

  • InputField in the MVC BSP app

    Hi, I am facing a weird problem with the Inputfield values in the BSP application which is developed using MVC architecture. When i try to enter a value in the inputfield, the value is preceeded by a space. by default looks like the inputfield value

  • Trouble importing photos onto iphoto

    Hi, I have been trying (without success) to download my photos from my Canon Ixus80 IS digital camera onto my iphotos. except it keeps coming up with the error - error downloading image. If I try to import the photos through image capture it also won

  • Transfering itunes library from one computer to another

    Can you transfer / copy itunes and all songs in library from one PC to another PC (only one IPOD in use