4 Replies Latest reply: Nov 8, 2012 2:35 PM by 935199 RSS

    Actions after synchronized block happens-after?

    935199
      Hi,

      I'd like to verify that my intuitive understanding of synchronization is correct here. I've read the Java language specification but I couldn't find anything in my example. This relates very loosely to the double-checking (anti)pattern.

      My question is specifically: Say I have the code:
      public void method() {
          synchronized(anyObject) {
              actionA();
          }
          actionB();
      }
      Does actionA() then have a happens-before relationship with actionB()?

      Thanks a lot!
        • 1. Re: Actions after synchronized block happens-after?
          jtahlborn
          you have the "happens-before" relationship reversed. generally, a synchronizing action establishes that all other preceding actions "happened-before" it. so, the synchronized block establishes a "happens-before" relationship with everything preceding actionA(). it says nothing about actionB().
          • 2. Re: Actions after synchronized block happens-after?
            935199
            Thanks, but I'm not sure I understand.

            In my intuition, if a thread enters method(), it must wait (possibly no time at all) to acquire the anyObject lock before it can execute actionB() from a program perspective.

            What I read in the Java Specs was "If x and y are actions of the same thread and x comes before y in program order, then hb(x, y)." I wasn't sure if a synchronized block counts as an "action" in this case.

            Let me rephrase my question to be more specific. For any given thread that enters method(), can I be sure that actionA() on that thread will execute before actionB() on the same thread?

            Thanks!

            Edited by: bombax on Nov 8, 2012 10:11 AM
            • 3. Re: Actions after synchronized block happens-after?
              jtahlborn
              bombax wrote:
              Let me rephrase my question to be more specific. For any given thread that enters method(), can I be sure that actionA() on that thread will execute before actionB() on the same thread?
              "happens-before" isn't so interesting in the context of a single thread. yes, for a single thread, all actions will appear to happen in the "program order", synchronized block or no.
              • 4. Re: Actions after synchronized block happens-after?
                935199
                Thanks! I know the question might have seemed obvious but your answer definitely helped.