Solved

static method and synchronized keyword

Posted on 2003-11-30
10
1,037 Views
Last Modified: 2013-11-24
Hello,

Could I get clarification on this ?

I have some static methods in Servlets that create objects locally but then pass them to another Servlets static methods for additional processing.

In the second Servlets static method do I have to synchronize on the input parameters in case several threads running through the first Servlet ask the second Servlet to do additional processing for them at the same time or is the second Servlets parameters safe as they were created locally in the first Servlet ?

Thanks !

0
Comment
Question by:klogger
  • 5
  • 5
10 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9846362
If the only place the static method is called is from your servlets synchronized method then you don't need to synchronize the static method.
0
 

Author Comment

by:klogger
ID: 9846431
Thanks for replying,

Does that mean that because I have the call coming from a doPost() which then calls a few other methods and finally ends up at what I called 'the second Servlet' (in my origonal question) then I never have to worry about sycnhronizing ?
0
 
LVL 92

Expert Comment

by:objects
ID: 9846438
can you post the relevant bits of code showing whats calling what, just to be sure.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:klogger
ID: 9846596
The servlet that receives the request from the JSP gets an 'action' parameter from the page and then looks up the correct servlet to handle the action from an xml file:

  public void doPost(HttpServletRequest req , HttpServletResponse res) throws ServletException , IOException {

        if(b_jvmRestarted){
            logger.fatal("THIS IS THE FIRST TIME Gateway HAS BEEN CALLED SINCE THE JVM WAS SUCCESSFULLY RESTARTED");
            b_jvmRestarted = false;
        }

        boolean validAction = false;
        String validClass;
        String increment = "";
        Hashtable ht_formFields = AddFormFields.toHashtable(req);
       
        String action = req.getParameter("action"); /* The value of action tells us that this is a login or eMail etc. */
        /* Check that the required class is valid by looking in gateway.xml
         */
        for(Enumeration e = configHashtable.keys() ; e.hasMoreElements() ;){
            validClass = (String)e.nextElement();
            if((action + "_servlet").equalsIgnoreCase(validClass)){
                validAction = true;
           }
        }
       
        if(!validAction){
            /* Value of hidden field action was not recognised so redirect to error page
             */
            GATEWAY_CLASS_NOT_VALID_PAGE = (String)configHashtable.get("gateway_class_not_valid_page");  
            logger.error("Value of acton in uk.co.prodia.Gateway was [" + action + "] value not recognised");
            res.sendRedirect(GATEWAY_CLASS_NOT_VALID_PAGE);
        } else {
            /* Handle the request
             */
            handleHttpRequest(req , res , ht_formFields , action);
        }
    }
   
    /* Allows the request to be handled by the correct servlet
     */
    private static void handleHttpRequest(HttpServletRequest req , HttpServletResponse res , Hashtable ht_formFields , String action){
        /* Get the values from the xml file
         */
        String  ACTION_HANDLER_CLASS = (String)configHashtable.get(action + "_servlet");
        PACKAGE_ROOT = (String) configHashtable.get("package_root");
        METHOD_ACTION_HANDLER = (String) configHashtable.get("method_action_handler");
           
        try {
            /* Create the class by reflection
             */
            Class actionHandlerClass = Class.forName(PACKAGE_ROOT + "." + ACTION_HANDLER_CLASS);
            Object actionHandlerObject = actionHandlerClass.newInstance();
            /* Create an empty Class[] so that we can use it to find the method that accepts the
             *
             * parameters we need
             */
            Class[] parameterTypes = new Class[] {HttpServletRequest.class , HttpServletResponse.class , Hashtable.class};
   
            /* Get the method we need bu finding a method with the correct name and parameter values
             * in the specified 'actionHandlerClass'
             */
            Method handlerMethod = actionHandlerClass.getMethod(METHOD_ACTION_HANDLER , parameterTypes);
            handlerMethod.invoke(actionHandlerObject , new Object[] {req , res , ht_formFields});
        } catch (Exception e) {
            logger.error(e);
        }
    }

The XML file tells the above servlet to pass the request to:

public class ShippingProviders {

public void handleAction(HttpServletRequest req , HttpServletResponse res , Hashtable ht_formFields){
        updateShippingProvider(req , res , ht_formFields);
    }

 public static Vector getShippingProvidersDetails(String s_shippingProvidersId){
       
        String s_getShippingProvidersDetails = "select * from shipping_providers where shipping_providers_id = '" + s_shippingProvidersId + "'";
       
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
       
         try{
            conn = DbConn.getConn();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(s_getShippingProvidersDetails);
           
            return SQLHelper.rsToVector(rs);
           
        } catch (Exception e){
            logger.error("Could not get shipping providers in getShippingProviders(). Exception is [" + e + "]");
        } finally {
            try{
               stmt.close();
               rs.close();
               conn.close();
            } catch (Exception ex){
                logger.error("Could not clean up in getShippingProviders(). Exception is [" + ex + "]");
            }
        }
       
        return null; /* On error */
    }

}

Which in it's method returns SQLHelper.rsToVector(rs).

SQLHelper.rsToVector(rs) is as follows:

  public static Vector rsToVector(ResultSet rs){

        if(rs == null) return new Vector();
       
        String columnName , rowValue;
        Vector queryResultsVector = new Vector();
        ResultSetMetaData rsmd = null;

        try{
            synchronized(rs){
                // Get meta data from the rs
                rsmd = rs.getMetaData();

                while(rs.next()){

                    Hashtable rsmdHashtable = new Hashtable(); // Do not change this line to rsmdHashtable.clear()
                    columnName = "";
                    rowValue = "";

                    /* Loop througth the rsmd and get the columnName and rowValue
                    */
                    for(int i = 0 ; i < rsmd.getColumnCount() ; i++){
                        columnName = rsmd.getColumnName(i + 1);
                        rowValue = rs.getString(i + 1);

                        /* Add the values to the hashtable that will be put in returnVector
                        */
                        if(rowValue != null) rsmdHashtable.put(columnName , rowValue);
                    }

                    /* Add the hashtable representing this rs row into a vector
                    *  then loop till each row in rs has a hashtable in queryResultsVector
                    */
                    queryResultsVector.addElement(rsmdHashtable);
               }
            }
           
        } catch (SQLException sqle){
            logger.error(sqle);
        }

        /* Return the formatted results
        */
        return queryResultsVector;
    }

and it is the input to SQLHelper.rsToVector(rs) that I was thinking of. I have synchronized it since asking the question but it wasn't synchronized before.

Thanks Objects.
0
 
LVL 92

Expert Comment

by:objects
ID: 9846629
I don't see any need to synchronize rsToVector as it only operates on local variable and doesn't share any.
0
 

Author Comment

by:klogger
ID: 9846650
Sorry ignore the above I became confused ! I will repost in a minute when I get my head straight.
Apologies.

0
 

Author Comment

by:klogger
ID: 9846654
Thanks objects - sorry for the confusion !
0
 

Author Comment

by:klogger
ID: 9846667
Right, so could I just clarify ?

Because the rs passed in SQLHelper is created as a local variable in another Servlet it can not be interfered with by another thread ?

0
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 9846695
correct
0
 
LVL 92

Expert Comment

by:objects
ID: 9846739
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question