Solved

static method and synchronized keyword

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

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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
topping1 challenge 7 53
wordcount challenge 11 78
for i loop in grovy 1 32
JDeveloper 12c for 32 bit 4 36
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This video teaches viewers about errors in exception handling.
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.

747 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

11 Experts available now in Live!

Get 1:1 Help Now