0

Below in try block, there are 3 statements must be executed in that order. Is there any possibility that statements could run out of order? Does JVM look ahead in j.u.c classes to see synchronization indicators (synchronized, volatile) and figure out it must not reorder the execution?

private Deque<Integer> deque = new LinkedList<Integer>();
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
class Producer implements Runnable {
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                deque.add(1);
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }
}
mert inan
  • 1,537
  • 2
  • 15
  • 26

2 Answers2

1

The JVM understands and obeys ordering such that you will not be able to observe anything illegal. It can (and will) take shortcuts in areas that are not observable to you. This is true both generally for Java code and specifically to j.u.c classes (where the JVM knows stuff such that it can further optimize while remaining safe.).

Trent Gray-Donald
  • 2,286
  • 14
  • 17
1

The JVM will never reorder function calls unless it has fully inlined them. Any side effect at all can hide behind them, so unless it can prove that this is not so, it cannot reorder them.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157