6

I have a class that is similar to this:

public class ExpensiveCalculation {
  private Executor threadExecutor = ...
  private Object lock = new Object();

  private Object data = null;

  public Object getData() {
    synchronized(lock) {
      return data;
    }
  }

  pulic void calculate() {
    executor.execute(() -> internalCalculation());
  }
  private void internalCalculation() {
    synchronized(lock) {
      // do some long running calculation that in the end updates data
      data = new Object();
    }
  }
}

This class makes some expensive (timewise) calculations and acquires a lock. While the lock is hold no one can retrieve the data that will be updated by the calculation, so in effect they have to wait for the calculation to finish. The actual calculation is done in a separate thread. If I have the following code:

ExpensiveCalculation calculation = ...
calculation.calculate();
Object data = calculation.getData();

The call to retrieve the data is blocked until the calculation is done. What exactly does waiting at this point mean?

  • Is it a busy waiting
  • Does the waiting thread yield, so other threads (like the one doing the computation) can proceed.
  • Does the waiting thread go to sleep?
  • Is wait/notify invoked behind the scene?

I am aware that for this example I could use a Callable and Future, but that is beside the point. Is there a way to improve such code, to ensure no time resources are wasted (like unnecessary thread switches)?

hotzst
  • 7,238
  • 9
  • 41
  • 64
  • Maybe [this](http://stackoverflow.com/questions/6584355/how-does-the-synchronize-functionnality-work-in-java) might help – MadProgrammer Jan 02 '16 at 08:54

1 Answers1

2

Is it a busy waiting

No.

Does the waiting thread yield, so other threads (like the one doing the computation) can proceed.

No, it blocks, so that other threads can run.

Does the waiting thread go to sleep?

It is blocked.

Is wait/notify invoked behind the scene?

No.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • If the calling thread yields, it will periodically get a slot where it is possible for it to try and acquire the lock. This would mean that it is possible that some time can pass between the release of `lock` from the calculation and the reacquiring of `lock` to retrieve the data. Is that correct? – hotzst Jan 02 '16 at 09:13
  • Actually, some sort of `wait/notify` mechanism is used, but this is low-level mechanism, which uses OS functionality. So waiter thread is blocked, until an event from predefined set occures. Releasing lock (in other thread) is one of such events, and after this event occures, waiter thread becomes immediately accessed for scheduling. – Tsyvarev Jan 02 '16 at 11:01