title: Does return "happen after" finally?
body: <p>I am trying to convince myself that actions taken in the <code>finally</code> clause <em>happen before</em> the function return (in the memory consistency sense). From the <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html" rel="nofollow noreferrer">JVM specification</a>, it is clear that within a thread, program order is supposed to drive the <em>happens before</em> relationship -- if <strong>a</strong> happens <strong>b</strong> in the program order then <strong>a</strong> <em>happens before</em> <strong>b</strong>.</p>
  
  <p>However, I have not seen anything explicitly stating that finally <em>happens before</em> return, so does it? Or, is there some way that the compiler could reorder the <code>finally</code> clause since it is simply logging.</p>
  
  <p>Motivating example: I have one thread fetching objects out of a database and am putting them into an ArrayBlockingQueue, and another thread is taking them out. I have some <code>try</code>- <code>finally</code> blocks for event timing, and I am seeing after affects of the return <strong>before</strong> the log statement</p>
  
  <p>Thread 1:</p>
  
  <pre><code>public Batch fetch() {
      try {
          log("fetch()+");
          return queryDatabase();
      }
      finally {
          log("fetch()-");
      }
       ...
      workQueue.put(fetch());
  </code></pre>
  
  <p>Thread 2:</p>
  
  <pre><code>log("take()+");
  Batch b = workQueue.take();
  log("take()-");
  </code></pre>
  
  <p>To my great surprise this prints out in an unexpected order. While, yes, logging statements in different threads can appear out of order, there is a time difference of at least 20&nbsp;ms.</p>
  
  <pre><code>124 ms : take()+
  224 ms : fetch()+
  244 ms : take()-
  254 ms : fetch()-
  </code></pre>
  
  <p>Note this is not exactly the same question as <a href="https://stackoverflow.com/questions/65035/in-java-does-return-trump-finally">does finally trump return</a>. I'm not asking what will be returned, but instead about memory consistency and execution order.</p>