简体   繁体   English

等待锁释放的方法如何?

[英]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. 我知道对于此示例,我可以使用Callable and Future ,但这Callable Is there a way to improve such code, to ensure no time resources are wasted (like unnecessary thread switches)? 有没有一种方法可以改进此类代码,以确保不浪费时间(例如不必要的线程切换)?

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. 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM