Solved

static method and synchronized keyword

Posted on 2003-11-30
10
1,036 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

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSum6 challenge 6 86
JUnit 4 @Before and @BeforeClass differences 3 59
Should localization be done inside spring controller 5 25
eclipse buid path vs tomcat lib path 10 22
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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.

813 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now