Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

static method and synchronized keyword

Posted on 2003-11-30
10
Medium Priority
?
1,042 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

610 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