Page 2 of 2 FirstFirst 12
Results 21 to 36 of 36
  1. #21
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    I don't normally do this sort of thing, but here is a skeleton for this, with some additional suggestions

    Java Code:
      public void run() {
        Connection conn = null;
        BufferedWriter writeBuffer = null;
        BufferedReader readBuffer = null
        try {
          conn = connectionPool.getConnection();
          // settings
          writeBuffer = ....;
          readBuffer = ....;
          String capturedInput;
          while ((capturedInput = readInput(readBuffer)) != null) {
            try {
              Statement stmt2 = conn.createStatement();
              try {
                ResultSet rs2 = stmt2.executeQuery(selectQuery2);
                try {
                  // do work possibly in another method to keep this one short
                } finally { try { rs2.close(); } catch (Throwable t) {} }
              } finally { try { stmt2.close(); } catch (Throwable t) {} }
              funct1(conn);
              funct2(conn);
              conn.commit();
            } catch (SQLException | IOException e2) {
              // log DB or input/output error
              try {
                conn.rollback();
              } catch (SQLException sqle) {
                // log rollback failure
              }
            }
          }
        } catch (SQLException | IOException e) {
          // log unable to get Connection or input/output open failure
        } finally {
          try { conn.close(); } catch (Throwable t) {}
          try { writeBuffer.close(); } catch (Throwable t) {}
          try { readBuffer.close(); } catch (Throwable t) {}
        }
      }
    
      public void funct1(Connection conn) throws SQLException {
        Statement stmt16 = conn.createStatement();
        try {
          ResultSet rs16 = stmt16.executeQuery(selectQuery16);
          try {
            // do work
          } finally { try { rs16.close(); } catch (Throwable t) {} }
        } finally { try { stmt16.close(); } catch (Throwable t) {} }
      }
    
      public void funct2(Connection conn) throws SQLException {
        Statement stmt18 = conn.createStatement();
        try {
          ResultSet rs18 = stmt18.executeQuery(selectQuery18);
          try {
            // do work
          } finally { try { rs18.close(); } catch (Throwable t) {} }
        } finally { try { stmt18.close(); } catch (Throwable t) {} }
      }
    
      public String readInput(BufferedReader br) throws IOException {
        // read input return String
        // return null when there is nothing to read
      }
    
      public void writeOutput(BufferedWriter bw, String dataToWrite) throws IOException {
        // write output
      }
    Edit: Also do not build the String using String concatenation as you are doing. In the readInput method declare a StringBuilder and use its append method and return a call to its toString() method.
    Last edited by masijade; 12-02-2013 at 11:24 AM.

  2. #22
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    This part cant be simplified further via any function right?

    try {
    Statement stmt2 = conn.createStatement();
    try {
    ResultSet rs2 = stmt2.executeQuery(selectQuery2);
    try {
    // do work possibly in another method to keep this one short
    } finally { try { rs2.close(); } catch (Throwable t) {} }
    } finally { try { stmt2.close(); } catch (Throwable t) {} }
    For the stringbuilder is this how it to be with the builder I got declare as global variable right?

    StringBuilder builder = new StringBuilder();
    builder.append((char) nextChar);
    return builder.toString();
    How does this logic replace apturedInput = readInput(readBuffer)) != null with (nextChar=r.read()) != -1?

  3. #23
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    To the first quote, yes, you can ALSO put that in another method, much like your "funct1" and the like, but simplified, no, just relocated.

    To the second quote, yes that is the right syntax, but used inside the readmethod and it doesn't replace it. simply inside the read method you do

    1. create stringbuilder
    2. your while loop with the -1
    3. call append rather than +=
    4. return toString

    so the "!= null" remains as it is, in my example
    and your while loop with the -1 goes inside readInput but using append rather than +=

    Edit: Now, get to work and modify your code and if it "doesn't work", than post back your new code with a COMPLETE description of what "doesn't work".

  4. #24
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    I have tried this.

    StringBuilder builder = new StringBuilder();
    int nextChar=0;
    while((nextChar=br.read())!=-1)
    {
    builder.append((char) nextChar);
    }
    return builder.toString();
    and this part too
    String capturedInput;
    while ((capturedInput = readInput(readBuffer)) != null)
    {
    System.out.println("Capute input is :"+capturedInput);
    but nothing gets printed not even this line of System.out.println("Capute input is :"+capturedInput); . I still dont get you what does this do (capturedInput = readInput(readBuffer)) != null . Does it take the whole buffer and send into the function and what is the !=null ?

  5. #25
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Post your new code please.

  6. #26
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    Below is my full codes.

    Java Code:
    public void run() { // etc
         BufferedWriter writeBuffer  = null;
         BufferedReader readBuffer  = null;  
         String message="";
         try {
             writeBuffer  =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
             readBuffer  = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
         
             int m = 0, count=0;
             int nextChar=0;
         
             System.out.println( "\n\n\n THE device"+" "+ receivedSocketConn1.getInetAddress() +":"+receivedSocketConn1.getPort()+" IS CONNECTED ");
    	     receivedSocketConn1.setSoTimeout(60000);
    	        String capturedInput;
    	        while ((capturedInput = readInput(readBuffer)) != null) 
    	         {	           	  
    	           	  System.out.println("Capute input is :"+capturedInput);
    	           	  
    	           	  /*message += (char) nextChar;  
    	           	   //n = n + (char) m;
    	           	  //  n = new StringBuffer().append((char)m).toString();
    	         	  int i = message.indexOf("GET");
    							if(i != -1) { 
    								break;
    							}
    				      if (nextChar == '*')
    				      {
    				      	
    				      }*/
    	         	
    	         }
    	         //closeConnection();
    	         System.out.println( "\n\n\n THE device close connection"+" "+ receivedSocketConn1.getInetAddress() +":"+receivedSocketConn1.getPort()+" IS CONNECTED ");
    	     
    	         System.out.println("\n\nDevice Closed The Connection Properly");
    	      }
    	      catch (SocketTimeoutException ex)  
    	      { 
    	           System.out.println("MyError:SocketTimeoutException has been caught in in the main first try");
    	           ex.printStackTrace();
    	      }  
    	      
    	      catch (Exception ex)  
    	      { 
    	           System.out.println( "\n\n\n THE device had exception problem"+" "+ receivedSocketConn1.getInetAddress() +":"+receivedSocketConn1.getPort()+" IS CONNECTED ");
    	     
    	           System.out.println("MyError:Exception has been caught in in the main first try");
    	           ex.printStackTrace(System.out);
    	      }      
    	      finally
    	      {
    	        try 
    	       	{
    	            System.out.println( "\n\n\n THE device is in finally"+" "+ receivedSocketConn1.getInetAddress() +":"+receivedSocketConn1.getPort()+" IS CONNECTED ");
    	     
    	            if ( writeBuffer  != null ) 
    		        {
    		          	writeBuffer .close();
    		        }
    		        else 
    		        {
    		        	System.out.println("MyError:writeBuffer  is null in finally close");
    		        }
    	        }
    	        catch(IOException ex){
    	           System.out.println("MyError:IOException has been caught in w in finally close");
    	           ex.printStackTrace(System.out);
    	        }
    	      }
          }
        
         
          public String readInput(BufferedReader br) throws IOException {
    	    StringBuilder builder = new StringBuilder();
    	    int nextChar=0;
    	    while((nextChar=br.read())!=-1)
    	    {
    		  builder.append((char) nextChar);
    	    }
    		return builder.toString();
    	  
    	}

  7. #27
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Add a println before the while loop in read input (just to say that it is about to read)
    then add a print(nextChar) inside the while loop to see what is read
    then add a println(builder) to see what builder contains

    And the != null is, essentially, the same as the != -1 in the other while loop.
    You are executing a method (readInput or read) and assigning that returned value to the variable, then checking that the value assigned to the variable is not equal to a specific value (null or -1).

    You need to change your return value in readInput though as follows:

    Java Code:
    if (builder.length() == 0) {
      return null;
    } else {
      return builder.toString();
    }
    Edit: Also, do not forget your "*" checks that you used as a separator token.

  8. #28
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    Here is my latest codes. Now the I can see the builder is building up the whole string by appending the individual character. But since I do the check for the '*' then I do the return there it gives me an error: missing return statement



    Java Code:
    public String readInput(BufferedReader br) throws IOException {
    	    StringBuilder builder = new StringBuilder();
    	    int nextChar=0;
    	    System.out.println("\n\nBefore the while loop");
    	    while((nextChar=br.read())!=-1)
    	    {
    		  System.out.println("\n\nnextChar is :"+(char) nextChar);
    		  System.out.println("\n\nbefore the builder is :"+builder.toString());
    		  builder.append((char) nextChar);
    		  System.out.println("\n\nafter the builder is :"+builder.toString());
    		  if((char) nextChar== '*')
    		  {
    		  	System.out.println("\n\nFinal value of builder is :"+builder.toString()+"  Length is :"+builder.length());
    		    if (builder.length() == 0) {
    			  return null;
    			} else {
    			  return builder.toString();
    			}
    		  }
    	    }

  9. #29
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Do the return OUTSIDE of the while loop, simply call break when you reach the "*" token.

  10. #30
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    Yes it is working now. Actually what is the benefit of string builder?

  11. #31
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,260
    Rep Power
    6

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Quote Originally Posted by newbie14 View Post
    Dear Masijade,
    Yes it is working now. Actually what is the benefit of string builder?
    Compared to what? A stringbuffer? Or to just appending String objects together?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #32
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Okay, when you concatenate Strings, as you were doing, Java, in the background, creates a StringBuffer (whose methods are synchronized) with the initial value of the original String, it then calls that StringBuffer's append method to do the "add" and then calls StringBuffer's toString method to produce the String, and it does this process for EVERY "+" on the line. Using StringBuilder directly (whose methods are NOT synchronized and so is a tick faster than StringBuffer) you avoid this process, thereby saving LOADS of "relative" time.

  13. #33
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    Thank you for the explanation hopefully I can see some speed improvement in my application. Will this have any impact on overall memory usage ?

  14. #34
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Not really. During the processing a VERY minor one, but generally negligible.

  15. #35
    newbie14 is offline Member
    Join Date
    Feb 2010
    Posts
    63
    Rep Power
    0

    Default Re: How to close resultset and statement in a finally when called in many functions?

    Dear Masijade,
    What else can be optimised as I already been using connection pooling do you think I also do socket pooling?

  16. #36
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: How to close resultset and statement in a finally when called in many functions?

    First, do you NEED to? Don't just guess as to what MIGHT or MIGHT NOT be a performance benefit. There are a few things that you SHOULD do (such as avoid String concatenation in all but the most minor and/or non-repeating sequences), but other then that run load tests and do profiling and THEN, using that data, figure out where you need to improve.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. If Statement Never Gets Called (SUPER EASY!)
    By skaterboy987 in forum New To Java
    Replies: 3
    Last Post: 10-16-2011, 04:44 AM
  2. Replies: 1
    Last Post: 05-17-2011, 10:43 AM
  3. Replies: 2
    Last Post: 10-08-2010, 01:08 PM
  4. Replies: 13
    Last Post: 04-09-2010, 12:15 PM
  5. Replies: 2
    Last Post: 07-18-2008, 02:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •