Java Code Examples for java.util.concurrent.locks.LockSupport#parkNanos()

The following examples show how to use java.util.concurrent.locks.LockSupport#parkNanos() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemoryRegistry.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 更新配置
 *
 * @param key    键
 * @param values 配置
 */
public void update(final String key, final Map<String, String> values) {
    if (key == null) {
        return;
    }
    AtomicReference<Config> ref = configDatum.computeIfAbsent(key, k -> new AtomicReference<>());
    Config oldDatum;
    long version;
    while (true) {
        oldDatum = ref.get();
        version = oldDatum == null ? 0 : oldDatum.getVersion() + 1;
        final Config newDatum = new Config(version, values == null ? new HashMap<>() : new HashMap<>(values));
        if (ref.compareAndSet(oldDatum, newDatum)) {
            state.whenOpen(c -> ((MemoryController) c).update(key, newDatum));
            return;
        }
        LockSupport.parkNanos(1);
    }
}
 
Example 2
Source File: BlockingStrategy.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
@Override
public void park(final long nanosToPark) throws InterruptedException {
    final long endNanos = System.nanoTime() + nanosToPark;
    long remainingParkNanos = nanosToPark;
    while (true) {
        LockSupport.parkNanos(remainingParkNanos);
        long currentTimeNanos = System.nanoTime();
        remainingParkNanos = endNanos - currentTimeNanos;
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        if (remainingParkNanos <= 0) {
            return;
        }
    }
}
 
Example 3
Source File: AsyncRSFlatMapPTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedMergeMap() {
    AtomicInteger data = new AtomicInteger(0);
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);

    range(0, 1000).mergeMap(
        v -> v % 2 == 0 ? Flux.just(v) : Flux.fromIterable(Arrays.asList(v))).forEach(n->{
        data.incrementAndGet();
    },e->{
        error.set(e);
    },()->{
        complete.set(true);
    });
    while(!complete.get()){
        LockSupport.parkNanos(10l);
    }

    assertThat(data.get(), CoreMatchers.equalTo(1000));
    assertTrue(complete.get());
    assertThat(error.get(), CoreMatchers.equalTo(null));
}
 
Example 4
Source File: InputStreamChannel.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Fill the given buffer reading data from channel at least one byte unless
 * end-of-stream has been reached.
 * 
 * @return number of bytes read or -1 on end-of-stream
 */
protected int readIntoBuffer(ByteBuffer buffer) throws IOException {
  long parkNanos = 0;
  int readBytes;
  while ((readBytes = this.channel.read(buffer)) == 0) {
    if (!buffer.hasRemaining()) {
      break;
    }
    // at this point we are out of the selector thread and don't want to
    // create unlimited size buffers upfront in selector, so will use simple
    // signalling between selector and this thread to proceed
    this.parkedThread = Thread.currentThread();
    LockSupport.parkNanos(this, PARK_NANOS);
    this.parkedThread = null;
    if ((parkNanos += PARK_NANOS) > PARK_NANOS_MAX) {
      throw new SocketTimeoutException("Connection read timed out.");
    }
  }
  return readBytes;
}
 
Example 5
Source File: LoadClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Record the event elapsed time to the histogram and delay initiation of the next event based
 * on the load distribution.
 */
void delay(long alreadyElapsed) {
  recorder.recordValue(alreadyElapsed);
  if (distribution != null) {
    long nextPermitted = Math.round(distribution.sample() * 1000000000.0);
    if (nextPermitted > alreadyElapsed) {
      LockSupport.parkNanos(nextPermitted - alreadyElapsed);
    }
  }
}
 
Example 6
Source File: BackoffIdleStrategy.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 *  {@inheritDoc}
 */
public void idle()
{
    switch (state)
    {
        case NOT_IDLE:
            state = SPINNING;
            spins++;
            break;

        case SPINNING:
            ThreadHints.onSpinWait();
            if (++spins > maxSpins)
            {
                state = YIELDING;
                yields = 0;
            }
            break;

        case YIELDING:
            if (++yields > maxYields)
            {
                state = PARKING;
                parkPeriodNs = minParkPeriodNs;
            }
            else
            {
                Thread.yield();
            }
            break;

        case PARKING:
            LockSupport.parkNanos(parkPeriodNs);
            parkPeriodNs = Math.min(parkPeriodNs << 1, maxParkPeriodNs);
            break;
    }
}
 
Example 7
Source File: UpgradableLock.java    From Carbonado with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if acquired
 */
private final boolean lockForWriteQueuedInterruptibly(L locker, final Node node,
                                                      long nanosTimeout)
    throws InterruptedException
{
    long lastTime = System.nanoTime();
    try {
        for (;;) {
            final Node p = node.predecessor();
            if (p == mRWHead && tryLockForWrite(locker)) {
                setReadWriteHead(node);
                p.mNext = null; // help GC
                return true;
            }
            if (nanosTimeout <= 0) {
                cancelAcquireReadWrite(node);
                return false;
            }
            if (nanosTimeout > SPIN_FOR_TIMEOUT_THRESHOLD
                && shouldParkAfterFailedAcquire(p, node))
            {
                LockSupport.parkNanos(this, nanosTimeout);
            }
            long now = System.nanoTime();
            nanosTimeout -= now - lastTime;
            lastTime = now;
            if (Thread.interrupted()) {
                break;
            }
        }
    } catch (RuntimeException e) {
        cancelAcquireReadWrite(node);
        throw e;
    }
    // Arrive here only if interrupted
    cancelAcquireReadWrite(node);
    throw new InterruptedException();
}
 
Example 8
Source File: SingleConsumerCondition.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void await(long millis) {
  if (Thread.currentThread() != consumer) {
    throw new RuntimeException("Wrong usage of SingleConsumerCondition: can only await in consumer thread.");
  }

  // NOTE: may spuriously return before deadline
  LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(millis));
}
 
Example 9
Source File: ThreadUtils.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public static void uncheckedSleep(long millis) {
    LockSupport.parkNanos(millis * 1000000);
    // we must check the interrupted status in case this is used in a loop
    // Otherwise we may end up spinning 100% without breaking out on an interruption
    if (Thread.currentThread().isInterrupted()) {
        throw new UncheckedInterruptedException();
    }
}
 
Example 10
Source File: HighPrecisionTimer.java    From ts3j with Apache License 2.0 5 votes vote down vote up
private boolean sleepFor(long nanos) {
	if (nanos > 0) {
		long elapsed = 0;
		while (elapsed < nanos) {
			long t0 = System.nanoTime();
			LockSupport.parkNanos(nanos - elapsed);
			elapsed += System.nanoTime() - t0;
		}

		return true;
	}

	return false;
}
 
Example 11
Source File: SynchronousQueue.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Spins/blocks until node s is fulfilled.
 *
 * @param s the waiting node
 * @param e the comparison value for checking match
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched item, or s if cancelled
 */
Object awaitFulfill(QNode s, E e, boolean timed, long nanos) {
    /* Same idea as TransferStack.awaitFulfill */
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = ((head.next == s) ?
                 (timed ? maxTimedSpins : maxUntimedSpins) : 0);
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel(e);
        Object x = s.item;
        if (x != e)
            return x;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel(e);
                continue;
            }
        }
        if (spins > 0)
            --spins;
        else if (s.waiter == null)
            s.waiter = w;
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanos);
    }
}
 
Example 12
Source File: SkipWhileOperatorTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void dropWhileStages3Async() {
    AtomicReference<Vector<Integer>> data = new AtomicReference(Vector.empty());
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);

    Subscription s = Spouts.async(ReactiveSeq.of(1,2,3,4,5),ex)
        .dropWhile(i -> i<2)
        .forEach(2, n -> {
            assertFalse(complete.get());
            data.updateAndGet(sq -> sq.plus(n));
        }, e -> {
            error.set(e);
        }, () -> {
            complete.set(true);
        });

    while(!complete.get()){
        LockSupport.parkNanos(10l);
    }

    assertThat(data.get(),equalTo(Vector.of(2,3,4,5)));
    assertThat(complete.get(),equalTo(true));
    assertNull(error.get());


}
 
Example 13
Source File: MpmcUnboundedXaddArrayQueuePeekTest.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        messageQueue.poll();

        if (messageQueue.size() < chunkSize) {
            LockSupport.parkNanos(sleepNanos);
        }
    }
}
 
Example 14
Source File: CoalescingStrategies.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static void parkLoop(long nanos)
{
    long now = System.nanoTime();
    final long timer = now + nanos;
    do
    {
        LockSupport.parkNanos(timer - now);
    }
    while (timer - (now = System.nanoTime()) > nanos / 16);
}
 
Example 15
Source File: Phaser.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
Example 16
Source File: QueuedSynchronizer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Acquires in shared timed mode.
 * 
 * @param arg
 *          the acquire argument
 * @param ownerId
 *          the lock owner, if any
 * @param lock
 *          the {@link TryLockObject} that will encapsulate the state of lock
 * @param nanosTimeout
 *          max wait time
 * @param context
 *          Any context object can be provided here (that can be passed to
 *          methods like
 *          {@link ExclusiveSharedSynchronizer#getOwnerId(Object)} by
 *          implementations of {@link TryLockObject}).
 * 
 * @return {@code true} if acquired
 */
private boolean doAcquireSharedNanos(final int arg, final Object ownerId,
    final TryLockObject lock, long nanosTimeout, final Object context,
    final CancelCriterion cc) {
  if (nanosTimeout <= 0L)
    return false;
  final long deadline = System.nanoTime() + nanosTimeout;
  final Node node = addWaiter(Node.SHARED);
  boolean failed = true;
  try {
    for (;;) {
      final Node p = node.predecessor();
      if (p == this.head) {
        final int r = lock.tryAcquireShared(arg, ownerId, context);
        if (r >= 0) {
          setHeadAndPropagate(node, r);
          p.next = null; // help GC
          failed = false;
          return true;
        }
      }
      nanosTimeout = deadline - System.nanoTime();
      if (nanosTimeout <= 0L)
        return false;
      if (shouldParkAfterFailedAcquire(p, node) &&
          nanosTimeout > spinForTimeoutThreshold)
        LockSupport.parkNanos(this, nanosTimeout);
      if (Thread.interrupted()) {
        handleInterrupted(cc);
        return false;
      }
    }
  } finally {
    if (failed) {
      cancelAcquire(node);
    }
  }
}
 
Example 17
Source File: SleepingWaitConditionStrategy.java    From java-Kcp with Apache License 2.0 5 votes vote down vote up
private int applyWaitMethod(int counter)
  {
  	if (counter > 100) {
	--counter;
} else if (counter > 0) {
	--counter;
	Thread.yield();
} else {
	LockSupport.parkNanos(1L);
}
return counter;
  }
 
Example 18
Source File: AbstractFuture.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
 * current thread is interrupted before or during the call, even if the value is already
 * available.
 *
 * @throws InterruptedException if the current thread was interrupted before or during the call
 *     (optional but recommended).
 * @throws CancellationException {@inheritDoc}
 */
@CanIgnoreReturnValue
@Override
public V get(long timeout, TimeUnit unit)
    throws InterruptedException, TimeoutException, ExecutionException {
  // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop
  // at the bottom and throw a timeoutexception.
  long remainingNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit.
  if (Thread.interrupted()) {
    throw new InterruptedException();
  }
  Object localValue = value;
  if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
    return getDoneValue(localValue);
  }
  // we delay calling nanoTime until we know we will need to either park or spin
  final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0;
  long_wait_loop:
  if (remainingNanos >= SPIN_THRESHOLD_NANOS) {
    Waiter oldHead = waiters;
    if (oldHead != Waiter.TOMBSTONE) {
      Waiter node = new Waiter();
      do {
        node.setNext(oldHead);
        if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
          while (true) {
            LockSupport.parkNanos(this, remainingNanos);
            // Check interruption first, if we woke up due to interruption we need to honor that.
            if (Thread.interrupted()) {
              removeWaiter(node);
              throw new InterruptedException();
            }

            // Otherwise re-read and check doneness. If we loop then it must have been a spurious
            // wakeup
            localValue = value;
            if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
              return getDoneValue(localValue);
            }

            // timed out?
            remainingNanos = endNanos - System.nanoTime();
            if (remainingNanos < SPIN_THRESHOLD_NANOS) {
              // Remove the waiter, one way or another we are done parking this thread.
              removeWaiter(node);
              break long_wait_loop; // jump down to the busy wait loop
            }
          }
        }
        oldHead = waiters; // re-read and loop.
      } while (oldHead != Waiter.TOMBSTONE);
    }
    // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
    // waiter.
    return getDoneValue(value);
  }
  // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the
  // waiters list
  while (remainingNanos > 0) {
    localValue = value;
    if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
      return getDoneValue(localValue);
    }
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    remainingNanos = endNanos - System.nanoTime();
  }
  throw new TimeoutException();
}
 
Example 19
Source File: SynchronousQueue.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Spins/blocks until node s is matched by a fulfill operation.
 *
 * @param s the waiting node
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched node, or s if cancelled
 */
SNode awaitFulfill(SNode s, boolean timed, long nanos) {
    /*
     * When a node/thread is about to block, it sets its waiter
     * field and then rechecks state at least one more time
     * before actually parking, thus covering race vs
     * fulfiller noticing that waiter is non-null so should be
     * woken.
     *
     * When invoked by nodes that appear at the point of call
     * to be at the head of the stack, calls to park are
     * preceded by spins to avoid blocking when producers and
     * consumers are arriving very close in time.  This can
     * happen enough to bother only on multiprocessors.
     *
     * The order of checks for returning out of main loop
     * reflects fact that interrupts have precedence over
     * normal returns, which have precedence over
     * timeouts. (So, on timeout, one last check for match is
     * done before giving up.) Except that calls from untimed
     * SynchronousQueue.{poll/offer} don't check interrupts
     * and don't wait at all, so are trapped in transfer
     * method rather than calling awaitFulfill.
     */
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = shouldSpin(s)
        ? (timed ? MAX_TIMED_SPINS : MAX_UNTIMED_SPINS)
        : 0;
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel();
        SNode m = s.match;
        if (m != null)
            return m;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel();
                continue;
            }
        }
        if (spins > 0) {
            Thread.onSpinWait();
            spins = shouldSpin(s) ? (spins - 1) : 0;
        }
        else if (s.waiter == null)
            s.waiter = w; // establish waiter so can park next iter
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > SPIN_FOR_TIMEOUT_THRESHOLD)
            LockSupport.parkNanos(this, nanos);
    }
}
 
Example 20
Source File: AbstractIOTestBase.java    From cyclops with Apache License 2.0 4 votes vote down vote up
@Test
public void onErrorEmptyIncremental(){
    AtomicInteger count = new AtomicInteger(0);
    AtomicBoolean data = new AtomicBoolean(false);
    AtomicReference<Vector<Integer>> result = new AtomicReference<>(Vector.empty());
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);



    Subscription sub = empty().<Integer>map(i -> {
        throw new RuntimeException();
    })
        .onError(e -> count.incrementAndGet())
        .forEach(0,n -> {
            result.updateAndGet(v->v.plus(n));
            data.set(true);
        }, e -> {
            error.set(e);
        }, () -> {
            complete.set(true);
        });

    assertThat(data.get(), equalTo(false));
    assertThat(complete.get(), equalTo(false));
    assertThat(error.get(), equalTo(null));
    assertThat(result.get(),equalTo(Vector.empty()));

    sub.request(1l);
    while(!complete.get()){
        LockSupport.parkNanos(10l);
    }
    assertThat(data.get(), equalTo(false));
    assertThat(complete.get(), equalTo(true));
    assertThat(error.get(), equalTo(null));
    assertThat(result.get(),equalTo(Vector.empty()));



    assertThat(count.get(),equalTo(0));

}