1 2 Previous Next 16 Replies Latest reply: Nov 4, 2004 11:00 AM by 807596 RSS

    Does code in finally block is executed immediately?

    807596
      Hi All:
      My question is same with my subject:
      Does code in finally block is executed immediately? especially in high volume environment.

      One of sun's engineer told me that the answer is no. Is this true? I don't belive this. I found lots of framework try to release resources in their finally block too. Does anybody have some experices about this.thanks.



        • 1. Re: Does code in finally block is executed immediately?
          807596
          What do you mean "immediately"? No matter how the execution flow leaves the portion code guarded with try - finally, whether normally of with an exception, the code in the finally clause will be executed, but it is not guaranteed that no thread context wil be switched, or that no garbage will be collected in the mean while etc.
          • 2. Re: Does code in finally block is executed immediately?
            807596
            You're confusing the finally clause and finalizers.
            See http://java.sun.com/docs/books/effective/ as a great reference.
            -Alexis
            • 3. Re: Does code in finally block is executed immediately?
              807596
              Hi Alexis, I do not mean finalizers. I do mean finally.
              Anyway thanks.

              I asked this question here because we may incur problems if resource is released in finally block after a long time in a high volume environment.
              For a uttermost example:
              There is 100 connections in a connection pool and there is a pseducode following:
              try{
              //retrive resouce
              //do other works
              }finally{
              //release connections and other resources.
              }

              So the problem is The 101th request may be blocked at the "retrive resource" phase if the finally block will be executed in a undetermined time.

              I know this problem should not be occured. But some engineers found such pseducode in our products will not release resources effectively in a high volume enviorment. According java's specification, It's so incomprehensible.:(. And i do not believe this also.

              Does anybody come with this problem? thanks
              • 4. Re: Does code in finally block is executed immediately?
                Herko_ter_Horst
                You can ready exactly what happens with try-catch-finally here:
                http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#236653

                There is no delay in executing the finally-part after the try-part has completed normally or with an exception (which will be handled first if there is a catch-clause that matches it). So if there are no exceptions, this
                try {
                  System.out.println("Try");
                } catch(Exception e) {
                  System.out.println("Catch");
                } finally {
                  System.out.println("Finally");
                }
                will behave as if you had written:
                System.out.println("Try");
                System.out.println("Finally");
                I guess the "Sun engineer" you asked asumed you were talking about object finalizers, which are not guaranteed to be called at any specific time, or at all.
                • 5. Re: Does code in finally block is executed immediately?
                  jschellSomeoneStoleMyAlias
                  >
                  I know this problem should not be occured. But some
                  engineers found such pseducode in our products will
                  not release resources effectively in a high volume
                  enviorment. According java's specification, It's so
                  incomprehensible.:(. And i do not believe this also.
                  Either you are not describing the problem correctly or the 'engineer' did not know what they were talking about.

                  There can be a delay in executing a finally block. Just as there can be a delay in executing any statement, in any language where threads are involved.

                  Now perhaps you are setting priorities. And it is the priority along with the way you use finally that is of concern.

                  But finally by itself is never going to cause an intermittent delay.

                  And if the engineer persists in that assertion then I suggest that you require a specific reference that backs it up.
                  • 6. Re: Does code in finally block is executed immediately?
                    807596
                    Hi Alexis, I do not mean finalizers. I do mean finally.
                    Anyway thanks.
                    Then the "engineer" meant finalizers, it's really what I think happened.
                    -Alexis
                    • 7. Re: Does code in finally block is executed immediately?
                      807596
                      Let's look at some generated code:
                      public class Finally {
                        void doIt ()
                        {
                          try {
                            int x = 42;
                            int y = x/0;
                          } catch (Exception e) {
                            e.printStackTrace();
                          } finally {
                            System.out.println("Got into finally!");
                          }
                        }
                      
                        public static void main ( String[] args ) {
                          Finally f = new Finally();
                          f.doIt();
                        }
                      }
                      produces the following bytecode:
                      $ javap -c Finally
                      Compiled from "Finally.java"
                      public class Finally extends java.lang.Object{
                      public Finally();
                        Code:
                         0:   aload_0
                         1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
                         4:   return
                      
                      void doIt();
                        Code:
                         0:   bipush  42
                         2:   istore_1
                         3:   iload_1
                         4:   iconst_0
                         5:   idiv
                         6:   istore_2
                         7:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
                         10:  ldc     #3; //String Got into finally!
                         12:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
                         15:  goto    45
                         18:  astore_1
                         19:  aload_1
                         20:  invokevirtual   #6; //Method java/lang/Exception.printStackTrace:()V
                         23:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
                         26:  ldc     #3; //String Got into finally!
                         28:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
                         31:  goto    45
                         34:  astore_3
                         35:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
                         38:  ldc     #3; //String Got into finally!
                         40:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
                         43:  aload_3
                         44:  athrow
                         45:  return
                        Exception table:
                         from   to  target type
                           0     7    18   Class java/lang/Exception
                      
                           0     7    34   any
                          18    23    34   any
                          34    35    34   any
                      
                      public static void main(java.lang.String[]);
                        Code:
                         0:   new     #7; //class Finally
                         3:   dup
                         4:   invokespecial   #8; //Method "<init>":()V
                         7:   astore_1
                         8:   aload_1
                         9:   invokevirtual   #9; //Method doIt:()V
                         12:  return
                      
                      }
                      Looks like the "finally" block is compiled into bytecode right after anywhere it might get executed. By the time the JVM is executing the bytecode, there's no way for it to even know that you had a "finally"!

                      Grant
                      • 8. Re: Does code in finally block is executed immediately?
                        807596
                        Hi eisenhower,

                        Did you get your answer? I think you are right; there is no guaranty that "finally" is called in high volume application. Please share your thoughts if you have the answer.

                        Thanks
                        • 9. Re: Does code in finally block is executed immediately?
                          807596
                          Doesn't Grant's post demonstrate the opposite?
                          -Alexis
                          • 10. Re: Does code in finally block is executed immediately?
                            jschellSomeoneStoleMyAlias
                            Did you get your answer? I think you are right; there
                            is no guaranty that "finally" is called in high
                            volume application. Please share your thoughts if you
                            have the answer.
                            Then feel free to post an example demonstrating that.

                            Or even post what processing steps might allow that.
                            • 11. Re: Does code in finally block is executed immediately?
                              jwenting
                              Hi eisenhower,

                              Did you get your answer? I think you are right; there
                              is no guaranty that "finally" is called in high
                              volume application. Please share your thoughts if you
                              have the answer.
                              finally is guaranteed to be called, finalize is not.
                              You seem to still be confusing the two...

                              finally is called on the end of executing a try-catch block irrespective of whether an exception occurred, finalize is called during garbage collection exactly once per class instance and garbage collection is never guaranteed.

                              NEITHER will be guaranteed to run at any specific time in your application as other threads may block the one in which your code is executing causing it to wait UNLESS you take specific measures like synchronisation.
                              • 12. Re: Does code in finally block is executed immediately?
                                807596
                                Hi All,
                                I want to ask one question regarding Finally block.
                                if my method returning some object and in finally block i m making that object null then will I get NULL in caller class or still i will get the reference ?
                                you can refer this code.

                                public DataSource getDataSource(String dsName) throws AppException {
                                DataSource ds = null;
                                try {
                                ResourceBundle resourceBundle = ResourceBundle.getBundle("resources.jdbc");
                                String datasource = resourceBundle.getString("datasource.prefix");      
                                InitialContext ctx = new InitialContext();

                                ds = (DataSource) ctx.lookup(datasource + dsName);
                                } catch (NamingException ne) {
                                     ExceptionHandler.handleException ("DatabaseConnection.getDataSource.NamingException",ne);
                                     
                                } catch (Exception e) {
                                     logger.error("Exception in DatabaseConnection");
                                     ExceptionHandler.handleException("DatabaseConnection.getDataSource.Exception", e);     
                                } finally {
                                ds = null;

                                }
                                return ds;
                                }
                                • 13. Re: Does code in finally block is executed immediately?
                                  807596
                                  The caller will obviously get whatever you are returning. Your finally block will always be executed and set ds to null, and you are returning ds, so... yes, you always return null in that case.
                                  • 14. Re: Does code in finally block is executed immediately?
                                    807596
                                    What if i were to do something like this? The finally does NOT get executed. Am I right? I have not seen any answers in the documentation about this and why the finally does not get executed.
                                    try
                                    {
                                      System.exit(0);
                                    }
                                    finally
                                    {
                                      System.out.println("finally!");
                                    }
                                    1 2 Previous Next