How to use TimeUnit.timedWait () without losing nanosecond accuracy?

I am trying to implement Future.get (long, TimeUnit) in terms of TimeUnit.timedWait (Object, long) .

It is not clear how to use it TimeUnit.timedWait(Object, long)in such a way as to process false awakenings without losing the nanosecond component of TimeUnit. Usually you do something like this:

public V get(long timeout, TimeUnit unit)
{
  long expirationTime = new Date().getTime() + unit.toMillis(timeout);
  while (!condition)
  {
    long timeLeft = expirationTime - new Date().getTime();
    if (timeLeft <= 0)
      throw new TimeoutException();
    unit.timedWait(object, timeLeft);
  }
}

but you will lose the nanosecond component. If everyone just discards the nanosecond component, then which point TimeUniteven supports nanoseconds and suggests TimeUnit.timedWait()?

+3
source share
3 answers

CountDownLatch :

public class MutableFuture<T> implements Future<T>
{
  private final CountDownLatch done = new CountDownLatch(1);
  private T value;
  private Throwable throwable;

  public synchronized boolean isDone()
  {
    return done.getCount() == 0;
  }

  public synchronized T get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException
  {
    if (!done.await(timeout, unit))
      throw new TimeoutException();
    if (throwable != null)
      throw new ExecutionException(throwable);
    return value;
  }

  // remaining methods left as exercise to the reader :)
}

CountdownLatch ( ).

+1

, , , -.

, - () , , , .

- , , , , , . - , , , ( -, ).

+3

Object.wait(long) spec:

, , -, . , , , , , . , , :

 synchronized (obj) {
     while (<condition does not hold>)
         obj.wait(timeout);
     ... // Perform action appropriate to condition
 }

(For more information on this, see section 3.2.3 in Doug Lea, “Parallel Programming in Java (Second Edition)” (Addison-Wesley, 2000) or paragraph 50 in Joshua Bloch, “Java Programming Language Guide” (Addison- Wesley, 2001).

+1
source

Source: https://habr.com/ru/post/1726810/


All Articles