Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the method waiting for the lock to be released?

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)?

like image 249
hotzst Avatar asked Jan 02 '16 08:01

hotzst


People also ask

Does wait method release lock?

The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.

Which method is used to release the lock held by an object?

"Calling notify() method on an object releases the lock of that object." and later "But when a thread calls notify() method on an object, the thread may not release the lock of that object immediately" in this answer contradict each other.

Which method releases the lock in thread?

A lock is acquired via the lock() method and released via the unlock() method. Invoking an unlock() without lock() will throw an exception.

Which method releases the lock in Java?

The unlock() method is another most common method which is used for releasing the lock. The unlock() method is a public method that returns nothing and takes no parameter. Syntax: public void unlock()


1 Answers

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.

like image 162
user207421 Avatar answered Sep 18 '22 17:09

user207421