Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just looking at your final example, I can't understand how you can say that is unsafe. How would anyone be able to tell the difference between the two? I think anything you tell me I'm just going to be able to answer 'but Java never guaranteed you that in the first place'. If nobody can tell the difference then how can it be unsafe?


>Just looking at your final example, I can't understand how you can say that is unsafe

Let me change the example a bit. Say we have two locks aL and bL, that we must always acquire in the order aL first and then bL.

Following the rule, say we write code like this:

  import java.util.concurrent.locks.ReentrantLock;
  class X {
    private static ReentrantLock aL = new ReentrantLock();
    private static ReentrantLock bL = new ReentrantLock();
    static int x = 0;
    static int c = 0;
    static public void main(String[] args) {
	for(aL.lock(); c < 100; c++) {
	  synchronized(bL) {
		x = x + 0x42;
	  }
	}
	aL.unlock();
    }
  }

If I understood it right, the blog post was asking a question whether JVM can transform this to:

  import java.util.concurrent.locks.ReentrantLock;
  class X {
    private static ReentrantLock aL = new ReentrantLock();
    private static ReentrantLock bL = new ReentrantLock();
    static int x = 0;
    static int c = 0;
    static public void main(String[] args) {
      synchronized(bL) {
        for(aL.lock(); c < 100; c++) {
            x = x + 0x42;
        }
        aL.unlock();
      } // end synnchronized
    }
  }
Since the locks are now acquired in a different order, does that not qualify as observable behavior?


But that's just a different example to the one you gave before. In your previous example acquiring the explicit lock always came before the start of synchronised block, both before and after the rewrite. You've changed it here so it's a different question.


Sorry, I meant to write:

  synchronized(this) {
    a = AcquireLock();
    for(c = 0; c < 100; c++) {
        f();
    }
  }
  ReleaseLock(a);
which is inline with what the blog post was proposing.

To repeat the blog is a question:

  for (...) {
    synchronized (obj) {
      // something
    }
  }
…​could it optimize into this?

  synchronized (this) {
    for (...) {
       // something
    }
  }
My answer to that is in general, no.


You mean because ... could be code that can detect whether or not the monitor is held?

Yes, but I think it's an assumption so obvious as to be not worth stating that the author means as long as ... does not do that.


> My answer to that is in general, no.

Because '...' can include arbitrary side-effect inducing statements that can't be moved around without affecting the behavior. As the poster discovered.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: