Synchronized (this)  inside a servlet

guys, is it wrong to use synchronized (this)" in a servlet????? what do you think will happen if this code is inside doPost in a servlet
synchronized (this) {
         this.wait(retry);
       }

Definitely do not synchronize on the servlet ... you can certainly restrict the granularity of the sycnronization ... you will be turning your servlet into a single threaded servlet ... yikes.
Anyway, I have synchronized on the session and for the most part it works. After some time I did run into some locking problems which I presume were because the container running in a different thread needed to acquire the lock on the session to do something ... just guessing.
Anyway, since then I have relied on a lock object that I place inside the session ... I lock on that object rather than on the session and have found this to work without any problem at all.

Similar Messages

  • Synchronized problem in JSP/Servlet, please help me.

    Hi, all
    I have many processes in one JSP page or Servlet program of my project.
    When many people visit at one time, then the project throws some SQL/DB Errors.
    I have updated it and test it many times, I think, that is a synchronized problem.
    At last I used ��synchronized (this){my JSP/Servlt SQL/DB processes}�� to synchronize
    The process. Then the errors removed.
    And now I think that too danger to use the ��synchronized (this){}�� to synchronized.
    If use it then some other problem may be growling on. Such as when one people need to use
    This service others must to wait, the process may be too slow! And when an exception throws
    from the SQL/DB or some other place, what I do? Need any advice from you.
    Sincerely
    Urey
    *** my JSP/Servlt Server is tomcat ***

    As Chuck points out, there isn't a new instance of the Servlet/JSP for each request - they are probably all calling the same instance so any state will be shared. If your Connection is stored as a member variable then you'll have problems with it already being in use if two people hit the page at the same time.
    Limited resources such as database connections should ideally be pooled anyway to ensure that you're not opening them all the time and that you can control how many are open across the entire application. Then you'd simply need to get a fresh connection out of the pool at the top of the page and make sure you put it back when you're done.
    Incidentally, although it might work, synchronizing the database access in the JSP would be a bad idea since you'd just create a queue of requests waiting to use the one Connection whereas you really need a number of Connections to deal with everyone simultaneously.
    If you need some example code for a simple JSP using a database connection pool (DataSource) just say.
    Hope this helps.

  • How do i create a single instance of a class inside a servlet ?

    how do i create a single instance of a class inside a servlet ?
    public void doGet(HttpServletRequest request,HttpServletResponseresponse) throws ServletException, IOException {
    // call a class here. this class should create only single instance, //though we know servlet are multithreaded. if, at any time 10 user comes //and access this servlet still there would one and only one instance of //that class.
    How do i make my class ? class is supposed to write some info to text file.

    i have a class MyClass. this class creates a thread.
    i just want to run MyClass only once in my servlet. i am afriad, if there are 10 users access this servlet ,then 10 Myclass instance wouldbe created. i just want to avoid this. i want to make only one instance of this class.
    How do i do ?
    they have this code in the link you provided.
    public class SingletonObject
      private SingletonObject()
        // no code req'd
      public static SingletonObject getSingletonObject()
        if (ref == null)
            // it's ok, we can call this constructor
            ref = new SingletonObject();          
        return ref;
      public Object clone()
         throws CloneNotSupportedException
        throw new CloneNotSupportedException();
        // that'll teach 'em
      private static SingletonObject ref;
    }i see, they are using clone !, i dont need this. do i ? shouldi delete that method ?
    where do i put my thread's run method in this snippet ?

  • Synchronizing DB updating in servlet

    hi,
    i'd like to the know what code I should synchronize when updating my database. I currently just have the lock as follows in a servlet:
    synchronized(this){
                statement.executeUpdate();
           }but i'm wondering if this is enough and if i should synchronize my
    statement.setString(x, x) calls?
    thanks

    Only one object at a time may access the synchronized block, so that will work fine.

  • Changing referer inside a servlet

    Hi,
    I have a servlet which send some html content to the client browser. from there it gets redirected to some site where i get the referer and the Url address of my servlet. Is there any was by which i can change the referer inside my servlet or the html content i send. so that after the redirection from the browser i need to see the referer which i have set.
    Thanks in advance !
    Pushpak

    try this:
    String referer = "blablabla";
    response.setHeader("Referer", referer);
    NB: you must do this before writing the content of your response body.

  • Which table stores this value Transmission Servlet Base URL

    Hi All,
    EBS r12 12.1.3
    From the screen in Payment
    Update Payment System: FirstDataNorth
    i am looking for table that stores this value
    Transmission Servlet Base URL
    did look in these tables FND_PROFILE*but not available.
    Please help!
    Regards,

    Hi,
    I am not sure, whether you are looking at the correct place. Can you also let us know what made you ask to check the infromation from table.
    But there are configuration file which stores these information. I believe the source we are looking info might be wrong.
    Also have a look at:
    Oracle Payments Implementation Guide
    Best Regards,

  • Unable to resolve this exception :javax.servlet.ServletException: No getter

    The source code I am having is
    1> Login.jsp
    2>LoginForm.java
    3>LoginAction.java
    4>web.xml
    5>struts-config.xml
    1>Login.jsp
    <%@ page language="java"%>
    <%@ page import="java.io.*"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <html:html>
    <center><IMG SRC="E:\jboss-4.0.3SP1\server\default\deploy\TestApplication.war\image\welcome.jpg" HEIGHT=233 WIDTH=282 ALT="WELCOME TO DATAMATICS"></center>
    <center><h1 style="color:blue"><hr>WELCOME TO DATAMATICS</hr></h1></center>
    <h2 style="color:green">LOGIN FORM</h2>
    <html:errors/>
    <center>
    <body>
         <html:form  action="/login.do"  >
         <table width="20%" border="0">
         <td>
              <tr><h4 style="color:red">USER ID:<h4></tr>
              <tr><html:text property="username" size="30"/></tr>
         <hr>
         </td>
         <td>
              <tr><h4 style="color:red">PASSWORD:</h4></tr>
              <tr><html:password property="password" size="30" /></tr>
         <hr>     
              <tr><html:submit>SUBMIT </html:submit></tr><hr>
              <tr><html:reset/></tr>
              <tr></tr>
         </td>
    </table>
    </body>
         </html:form>
    </center>
    </html:html>------------------------------------------------------
    2>LoginForm.java
    package com.MyPack.Datamatics;
    import com.MyPack.Datamatics.LoginAction;
    import javax.servlet.http.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action.*;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionError.*;
    //import java.util.*;
    //import java.io.*;
    public class LoginForm extends ActionForm
         private String username=null;
         private String password=null;
         public void setUserName(String username)
              this.username=username;
         public String getUserName()
              return username;
         public void setPassword(String password)
              this.password=password;
         public String getPassword()
              return password;
         public void reset(ActionMapping am,HttpServletRequest req)
              this.username="";
              this.password="";
         public ActionErrors validate(ActionMapping am, HttpServletRequest req)
              ActionErrors ae = new ActionErrors();
              if ( (username==null) || (username.length()==0))
         //     ae.add("username" , new ActionMessage("errors.username.required") );
              if( (password==null) || (password.length()==0))
         //     ae.add("password" , new ActionMessage("errors.password.required") );
         return ae;          
    3>LoginAction.java
    package com.MyPack.Datamatics;
    import com.MyPack.Datamatics.LoginForm;
    import javax.servlet.http.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import javax.servlet.ServletException;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionError;
    public class LoginAction extends Action
         public ActionForward execute(ActionMapping am,
                                             ActionForm af,
                                             HttpServletRequest req,
                                             HttpServletResponse res)throws IOException, ServletException
              String target= new String("success");
              if(af!=null)
              LoginForm loginForm = (LoginForm)af;
              String userName = loginForm.getUserName();
              String password = loginForm.getPassword();
              if (userName.equalsIgnoreCase("Datamatics") && password.equalsIgnoreCase("12345"))
                   req.setAttribute("UserName",userName);
              else
                        target = new String("failure");          
         return am.findForward(target);
    4>web.xml
    <web-app>
         <servlet>
              <servlet-name>ActionServlet</servlet-name>
              <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
         <init-param>
              <param-name>config </param-name>
              <param-value>/WEB-INF/struts-config.xml</param-value>
         </init-param>
         <init-param>
              <param-name>application </param-name>
              <param-value>ApplicationResources</param-value>
         </init-param>
         <load-on-startup>2</load-on-startup>
         </servlet>
         <servlet-mappings>
              <servlet-name>ActionServlet</servlet-name>
              <url-mapping>*.do</url-mapping>
         </servlet-mappings>
         <taglib>
             <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
             <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
           </taglib>
        <taglib>
           <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
           <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
        </taglib>
       <taglib>
          <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
          <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
       </taglib>
    </web-app>-----------------------
    5>Struts-config.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <struts-config>
         <form-beans>
              <form-bean name="loginForm" type="com.MyPack.Datamatics.LoginForm"  />
              <form-bean name="uploadForm" type="com.MyPack.Datamatics.UploadForm" />
         </form-beans>
         <global-forwards>
              <forward name="success" path="/index.jsp"/>
         </global-forwards>
         <action-mappings>
              <action path="/login"
                        type="com.MyPack.Datamatics.LoginAction"
                        name="loginForm"
                        scope="request"
                        input="/login.jsp">
                   <forward name="success" path="/upload.jsp" />
                   <forward name="fail" path="/index.jsp" />
              </action>
              <action path="/upload"
                        type="com.MyPack.Datamatics.UploadAction"
                        name="uploadForm"
                        scope="request"
                        input="/upload.jsp">
                   <forward name="success" path="/successUpload.jsp" />
                   <forward name="fail" path="/index.jsp" />
              </action>
         </action-mappings>
    <controller
    processorClass="org.apache.struts.action.RequestProcessor"/>
    </struts-config>Kindly help where i am going wrong ..... I have mapped every property, even though I am getting this error
    :::::::>> javax.servlet.ServletException: No getter

    Error come from your LogonForm.
    Field: username So getter must be getUsername() and not getUserName() ("N" is lower case).

  • How to Buffer JSP Output Inside A Servlet

    Hello, we are trying to Process a JSP page inside a servlet and then do more processing and finnaly add the JSP output to the response output stream. I know there is a RequestDispatcher that lets you include a JSP page. However as far as I know all you can do with the RequestDispatcher is either include the JSP (which does not buffer it but simply adds it to the output stream) or forward to the JSP page. Any ideas? Thanks, - dk

    http://forum.java.sun.com/thread.jsp?forum=33&thread=377214

  • I have an ipod nano and its fall down , the inside screen is broken..... can APPLE replace this(inside screen)???!

    i have an ipod nano and its fall down , the inside screen is broken..... can APPLE replace this(inside screen)???!

    Hello Alia A,
    Sorry to hear about your iPod nano screen.  I recommend reviewing the following link for service options (you can update the country selection to your location after accessing the link):
    Service Answer Center - iPod
    http://support.apple.com/kb/index?page=servicefaq&geo=United_States&product=ipod
    Thank you for using Apple Support Communities.
    Best,
    Sheila M.

  • What is wrong with synchronized(this)?

    Is there anything wrong with this?
    synchronized(this)I have try to do the following with a monitor object, but I get IllegalMonitoreStateException: current thread not owner when using:
    synchronized (MONITOR) {
         while (isSuspended && workerThread == thisWorker) {                              
              try {
                   wait();               
              } catch (InterruptedException x) {
                   x = null; // ignored
    ...

    You need to wait on that which you own the monitor lock.
    synchronized(this)
      try {
         wait();               
      } catch (InterruptedException x) {
    }or
    Object MONITOR = new Object();
    synchronized(MONITOR)
      try {
         MONITOR.wait();               
      } catch (InterruptedException x) {
    }

  • Synchronized (this)

    if (_jspx_inited == false) {
    synchronized (this) {
    if (_jspx_inited == false) {
    jspxinit();
    jspxinited = true;
    what does this keyword do here?

    see mr...i don know if i sound arragant or not...i
    am doing reseach on this keyword ..thats y i am
    asking all the possible things...in case u don like
    to answer u are most welcome.. dont be arragant
    ....first u learn how to beI do agree a bit with the previous poster. Many of your question can be answered by reading a tutorial or beginners book.
    You are also cross-posting some of the questions, and that is bad manners.
    /Kaj

  • Synchronized( this ) vs synchronized( SomeClass.class )

    I have seen synchronized bits of code declared in the following ways:
    1)
    synchronized( this )
      //some stuff
    }2)
    synchronized( SomeClass.class )
      //some stuff
    }Could anyone explain the diference or tell me where to read about it.
    Thanks In Adavance!

    Mattbunch is correct, but I will also check later.
    If you want to lock on a class level you lock on a
    static method.The term "locking on a class level" doesn't really mean anything.
    In the original post, the only difference betweensynchronized this() {} and synchronized(SomeClass.class) {} is which object they use as a lock. That's the only difference. There's no difference in what gets protected or how.
    Static methods are at the class scope, global, and
    they are locked for the class, not just the
    instance, understand?Again, that statement--the concept of being "locked for the class vs. for the instance"--doesn't really have any meaning. If you declare a static method synchronized, it obtains one particular object's lock (that of the Class object corresponding to that method's class), and if you declare an instance method syncrhonized, it obtains a different object's lock--that of the intstance whose method you're calling. That's the only difference--which lock you obtain. There's no inherent difference in the scope of the "protection".
    Also remember that locking on the static methods does
    not prevent another thread from entering a non static
    public method.You don't "lock on" a method. But assuming you mean "declaring a static method synchronized," it doesn't stop another thread from entering any other unsynchronized method, static or not, public or not, and it doesn't stop a thread from entering any synchronized instance method. It only stops threads from entering blocks or methods syncrhronized on the Class object for that class.

  • Accessing a binding from inside a servlet

    Hey all,
    So I'm attempting to access a binding from a servlet instead of using the ApplicationModule approach which is recognized as a bad idea (http://blogs.oracle.com/jdevotnharvest/2010/11/when_to_use_createrootapplicationmodule_in_oracle_adf.html). However, when the code is executing in the servlet the line BindingContent.getCurrentBindingsEntry() returns null! I think there's something missing in my configuration that's causing ADFm to not recognize the servlet as having a binding file. Anything stand out?
    So inside of a servlet I have the following:
    public class RSSNewsServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    BindingContext bctx = BindingContext.getCurrent();
    BindingContainer bindings = bctx.getCurrentBindingsEntry();
    DCBindingContainer bindingsImpl = (DCBindingContainer)bindings;
    DCIteratorBinding dciter = bindingsImpl.findIteratorBinding("AllPapers1Iterator");
    Row [] rows = dciter.getAllRowsInRange();
    Web.xml:
    <filter-mapping>
    <filter-name>adfBindings</filter-name>
    <servlet-name>NewsServlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    <servlet>
    <servlet-name>NewsServlet</servlet-name>
    <servlet-class><path-to-servlet>.RSSNewsServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>NewsServlet</servlet-name>
    <url-pattern>/servlet/news.rss</url-pattern>
    </servlet-mapping>
    newsServletPageDef.xml:
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
    version="11.1.1.56.60" id="newsServletPageDef"
    Package="<path-to-pagedefs>pageDefs">
    <parameters/>
    <executables>
    <variableIterator id="variables"/>
    <iterator Binds="AllPapers1" RangeSize="25"
    DataControl="GatewayNewsAppModuleDataControl"
    id="AllPapers1Iterator"/>
    </executables>
    <bindings>
    <tree IterBinding="AllPapers1Iterator" id="AllPapers1">
    <nodeDefinition DefName="<path-to-model>AllPapers"
    Name="AllPapers10">
    <AttrNames>
    <Item Value="PapId"/>
    <Item Value="PapTitle"/>
    <Item Value="PapPublishDate"/>
    <Item Value="PapExpireDate"/>
    <Item Value="PapAuthor"/>
    <Item Value="PapType"/>
    <Item Value="PapIssueDate"/>
    <Item Value="PapFileName"/>
    <Item Value="PapUserName"/>
    <Item Value="PapPostedDate"/>
    <Item Value="PapModifiedDate"/>
    <Item Value="PapNeverExpire"/>
    <Item Value="PapFile"/>
    </AttrNames>
    </nodeDefinition>
    </tree>
    </bindings>
    </pageDefinition>
    DataBindings.cpx:
    <pageMap>
    <page path="/servlet/news.rss" usageId="MyAlmacTemplate_view_newsServletPageDef"/>
    </pageMap>
    <pageDefinitionUsages>
    <page id="MyAlmacTemplate_view_newsServletPageDef"
    path="com.almac.aurora.gateway.pageDefs.newsServletPageDef"/>
    </pageDefinitionUsages>

    when the code is executing in the servlet the line BindingContent.getCurrentBindingsEntry() returns null!The method BindingContext.getCurrentBindingsEntry() returns from the requestScope the variable with key "bindings". When using ADF Faces this variable is set at ADF Faces' Prepare Model phase (by the PageLifecycleImpl.prepareModel() method). But when using a plain servlet this variable is not set (because the ADF Faces' page lifecycle is not executed) and this is the reason why you get a null result. As a workaround you can use the following code in your servlet:
    BindingContext bctx = BindingContext.getCurrent();
    DCBindingContainer pagedef = bctx.findBindingContainerByPath(request.getServletPath());
    bctx.setCurrentBindingsEntry(pagedef); // Invoke this method only if for some reason you need the "bindings" variable set in the environmentDimitar

  • Processing requests in a separate worker thread created inside a servlet.

    Scenario:
    We have an action that needs to be initiated by a servlet, but will take some time to accomplish and so the servlet should just hand it off to a separate thread for actual processing, and the servlet should just respond immediately with a redirect to a JSP page that outputs a simple message saying the action has been initiated and current date and time.
    Task:
    So, create a servlet that accepts a parameter in the request (both POST and GET requests should be supported) and set up a separate worker thread (set one up in the init() method of the servlet) that it will hand off requests to. The servlet will call into the worker thread passing it the parameter value which will be put on the worker thread's queue.
    The worker thread should stay asleep until it receives requests. Any requests will wake up the worker thread which will then process it's queue. The action would be a long running process, but for this test, it will just be to log a message to System.out including the parameter value and the current timestamp.
    Please ensure that concurrency issues are handled correctly.

    I'll get right on that.
    Give me your professor's email address and I'll even send it directly to him. You won't have to lift a finger.
    Krum

  • Server inside a servlet

    i have a servlet which creates a server which listens on a free port (i create a Socket). the server is created in the init() method of the servlet.
    in the doGet() method i upload an applet which finaly may try to connect to this server.
    the applet is loaded, but when it tries to connect to the server through the specific socket it fails and get an IOException - connection refused.
    As i managed to understand the servlet does not exist ufter the applets load. how do i make the server keep running ufter the applet has been loaded ? or is there a better way besides using init()?

    When do you start your server? Is your Socket object declared as a servlet member, or declared only in the init() method?
    If it's only declared in the init() method, then after the init() method finishes the Socket will be garbage-collected, which wuld explain why nobody can connect to it anymore.

Maybe you are looking for

  • Order ETDAT Extraction to BW

    Hello experts, As you know in an order there is a date for each item called "FIRST DATE" with the technical name ETDAT. I need to extract this date per item but I can not find the date in the LIS Extractor. I also tried to find the ETDAT with the use

  • Download Photoshop CS3

    I am trying to download Photoshop CS3 as I do not have a disc drive in my macbook pro - but the link below is not working. Is there somewhere else I can download? or is not possible to download anymore? help!! thanks http://esd.adobe.com/Applications

  • Shrink Text from 16:9 to 4:3

    Hi. I have some 4:3 menus which I created. They include text layers. I'd like to keep the same menu layout for a 16:9. When changing the menu within Encore from 4:3 to 16:9, the aspect ratio of the text layers are changed as well. This is _not_ desir

  • Transfer MS project scheduling to SAP

    I want to transfer MS Project Scheduling to SAP PS. How it can be done ? Regards, Ashish

  • Stupid SQL SELECT tricks

    Need help with this query. I'm using group by and rollup to get sub totals and a total. My problem is it's duplicating the middle values in the column and I'm not sure how to remove the middle dup value for the under_sec_sym. I'm sure this is an easy