Java 可等待对象容器

Java waitable object container

是否有实施以下方法的现有框架?

public class WaitableContainer<T> {
  private T object;
  public <T> peekAwait() {...} // returns object if object !=null or makes the caller thread sleep until object != null
  public actuate(T object) {
    this.object = object; // here all sleeping threads must awake and receive the new object
  }
}

需要某种对象包装器,使调用者线程停止运行,直到另一个线程设置该对象。

这听起来像 CompletableFuture

// container.actuate(o); becomes
future.complete(o);

// container.peekAwait(); becomes
future.get();

如果您不能使用 Java 8,FutureTask 是一个不错的解决方法,但与其显式设置它,不如提供一个 returns 值的 Callable你要设置。

final FutureTask<Object> lazyLoadedData = new FutureTask<>(() -> expensiveIO());

...

if (!lazyLoadedData.isDone()) {
    synchronized(lazyLoadedData) {
        if (!lazyLoadedData.isDone()) {
            // run() does the computation and sets the data
            // essentially, lazyLoadedData.set(expensiveIO())
            lazyLoadedData.run();
        }
    }
}
// Data is available
lazyLoadedData.get();

如果您计划让 ExecutorService 执行此操作,它已经 returns 一个未来;

final FutureTask<Object> future = executorService.submit(() -> expensiveIO());

// Now you just need to call get()
future.get();