?
Solved

static method and synchronized keyword

Posted on 2003-11-30
10
Medium Priority
?
1,040 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 1000 total points
ID: 9846695
correct
0
 
LVL 92

Expert Comment

by:objects
ID: 9846739
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month9 days, 15 hours left to enroll

762 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