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

The following are Jave code examples for showing how to use parkNanos() of the java.util.concurrent.locks.LockSupport class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: mycat-src-1.6.1-RELEASE   File: SleepingWaitStrategy.java   View Source Code Vote up 6 votes
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
        throws AlertException {
    //检查是否需要终止
    barrier.checkAlert();
    //如果在200~100,重试
    if (counter > 100) {
        --counter;
    }
    //如果在100~0,调用Thread.yield()让出CPU
    else if (counter > 0) {
        --counter;
        Thread.yield();
    }
    //<0的话,利用LockSupport.parkNanos(1L)来sleep最小时间
    else {
        LockSupport.parkNanos(1L);
    }
    return counter;
}
 
Example 2
Project: dxram   File: AbstractPipeIn.java   View Source Code Vote up 6 votes
/**
 * Enter a new buffer slot. Is called by MessageCreationCoordinator.
 *
 * @param p_incomingBuffer
 *         the new incoming buffer
 * @param p_slot
 *         the slot to enter
 * @return the message counter used for this slot
 */
private AtomicInteger enterBufferSlot(IncomingBufferQueue.IncomingBuffer p_incomingBuffer, final int p_slot) {

    // #ifdef STATISTICS
    SOP_WAIT_SLOT.enter();
    // #endif /* STATISTICS */

    // Wait if current slot is processed
    while (m_slotMessageCounters[p_slot].get() > 0) {
        LockSupport.parkNanos(100);
    }

    // #ifdef STATISTICS
    SOP_WAIT_SLOT.leave();
    // #endif /* STATISTICS */

    // Get slot message counter
    AtomicInteger messageCounter = m_slotMessageCounters[p_slot];
    // Avoid returning buffer too early by message handler; message counter is decremented at the end
    messageCounter.set(2 * m_messageHandlerPoolSize);
    // Set buffer (NIO/Loopback) and buffer handle (IB) for message handlers
    m_slotBufferWrappers[p_slot] = p_incomingBuffer.getDirectBuffer();
    m_slotBufferHandles[p_slot] = p_incomingBuffer.getBufferHandle();

    return messageCounter;
}
 
Example 3
Project: java-concurrency-cheatsheet   File: Main.java   View Source Code Vote up 6 votes
@Override
public void run() {
    synchronized (u) {
        System.out.printf("%s in %s\n", new Date(), getName());
        LockSupport.park(u);
        if (isInterrupted()) {
            System.out.println(getName() + " is interrupted.");
        }
    }

    // 最多阻塞 5 s
    // 如果中断位为 true,则下面的语句无效,可以对比上面如果是使用 Thread.interrupted() 方法判断有什么不同
    LockSupport.parkNanos(this, TimeUnit.SECONDS.toNanos(5));

    System.out.printf("%s %s ends\n", new Date(), getName());
}
 
Example 4
Project: dble   File: ShowBinlogStatus.java   View Source Code Vote up 5 votes
/**
 * getQueryResult: show master status
 *
 * @param charset
 */
private static void getQueryResult(final String charset) {
    Collection<PhysicalDBPool> allPools = DbleServer.getInstance().getConfig().getDataHosts().values();
    sourceCount = new AtomicInteger(allPools.size());
    rows = new ArrayList<>(allPools.size());
    for (PhysicalDBPool pool : allPools) {
        //if WRITE_RANDOM_NODE ,may the binlog is not ready.
        final PhysicalDatasource source = pool.getSource();
        OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler(FIELDS,
                new SQLQueryResultListener<SQLQueryResult<Map<String, String>>>() {
                    @Override
                    public void onResult(SQLQueryResult<Map<String, String>> result) {
                        String url = source.getConfig().getUrl();
                        if (!result.isSuccess()) {
                            errMsg = "Getting binlog status from this instance[" + url + "] is failed";
                        } else {
                            rows.add(getRow(url, result.getResult(), charset));
                        }
                        sourceCount.decrementAndGet();
                    }

                });
        SQLJob sqlJob = new SQLJob(SHOW_BINLOG_QUERY, pool.getSchemas()[0], resultHandler, source);
        sqlJob.run();
    }
    while (sourceCount.get() > 0) {
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
    }
}
 
Example 5
Project: atomic   File: AtomicLongArray.java   View Source Code Vote up 5 votes
private boolean compareAndSetRaw(long offset, long expect, long update) {
    if (unsafe.compareAndSwapLong(array, offset, expect, update)) {
        return true;
    }
    LockSupport.parkNanos(1);
    return false;
}
 
Example 6
Project: openjdk-jdk10   File: Phaser.java   View Source Code Vote up 5 votes
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
Example 7
Project: mycat-src-1.6.1-RELEASE   File: SingleProducerSequencer.java   View Source Code Vote up 5 votes
@Override
public long next(int n) {
    if (n < 1) {
        throw new IllegalArgumentException("n must be > 0");
    }

    long nextValue = this.nextValue;
    //next方法和之前的hasAvailableCapacity同理,只不过这里是相当于阻塞的
    long nextSequence = nextValue + n;
    long wrapPoint = nextSequence - bufferSize;
    long cachedGatingSequence = this.cachedValue;

    if (wrapPoint > cachedGatingSequence || cachedGatingSequence > nextValue) {
        long minSequence;
        //只要wrapPoint大于最小的gatingSequences,那么不断唤醒消费者去消费,并利用LockSupport让出CPU,直到wrapPoint不大于最小的gatingSequences
        while (wrapPoint > (minSequence = Util.getMinimumSequence(gatingSequences, nextValue))) {
            waitStrategy.signalAllWhenBlocking();
            LockSupport.parkNanos(1L); // TODO: Use waitStrategy to spin?
        }
        //同理,缓存最小的gatingSequences
        this.cachedValue = minSequence;
    }

    this.nextValue = nextSequence;

    return nextSequence;
}
 
Example 8
Project: canal-elasticsearch   File: LockTest.java   View Source Code Vote up 5 votes
private static void applyWait(int emptyTimes) throws InterruptedException {
    int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
    if (emptyTimes >= 3) {
        Thread.yield();
        LockSupport.parkNanos(10000 * 1000L * newEmptyTimes);
    }
}
 
Example 9
Project: java-restclient   File: RestClientAsyncRetryTest.java   View Source Code Vote up 5 votes
@Test(expected = ExecutionException.class)
public void shouldRetryOnMakeResponseException() throws RestException, ExecutionException, InterruptedException {
    String url = "http://dummy.com/test";

    MockResponse.builder()
            .withURL(url)
            .withMethod(POST)
            .withStatusCode(201)
            .withResponseHeader(ContentType.HEADER_NAME, ContentType.TEXT_PLAIN.toString())
            .withResponseBody(DummyCallbackProcessor.THROW)
            .build();

    final AtomicInteger retries = new AtomicInteger();

    Future<Response> response = RestClient.getDefault().withRetryStrategy(new RetryStrategy() {
        @Override
        public RetryResponse shouldRetry(Request req, Response r, Exception e, int rs) {
            retries.getAndIncrement();
            return new RetryResponse(false, 0);
        }
    }).asyncPost(url);

    LockSupport.parkNanos(2000000);

    assertEquals(1, retries.get());

    response.get();
}
 
Example 10
Project: jdk8u-jdk   File: FutureTask.java   View Source Code Vote up 5 votes
/**
 * Awaits completion or aborts on interrupt or timeout.
 *
 * @param timed true if use timed waits
 * @param nanos time to wait, if timed
 * @return state upon completion
 */
private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) // cannot time out yet
            Thread.yield();
        else if (q == null)
            q = new WaitNode();
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            LockSupport.parkNanos(this, nanos);
        }
        else
            LockSupport.park(this);
    }
}
 
Example 11
Project: dxram   File: MessageCreationCoordinator.java   View Source Code Vote up 5 votes
@Override
public void run() {
    IncomingBufferQueue.IncomingBuffer incomingBuffer;
    int counter = 0;
    long lastSuccessfulPop = 0;

    while (!m_shutdown) {
        // pop an incomingBuffer
        incomingBuffer = m_bufferQueue.popBuffer();
        if (incomingBuffer == null) {
            // Ring-buffer is empty.
            if (++counter >= THRESHOLD_TIME_CHECK) {
                if (System.currentTimeMillis() - lastSuccessfulPop > 1000) { // No message header for over a second -> sleep
                    LockSupport.parkNanos(100);
                }
            }

            if (m_overprovisioning) {
                Thread.yield();
            }
            continue;
        }
        lastSuccessfulPop = System.currentTimeMillis();
        counter = 0;

        try {
            incomingBuffer.getPipeIn().processBuffer(incomingBuffer);
        } catch (final NetworkException e) {
            incomingBuffer.getPipeIn().returnProcessedBuffer(incomingBuffer.getDirectBuffer(), incomingBuffer.getBufferHandle());

            // #if LOGGER == ERROR
            LOGGER.error("Processing incoming buffer failed", e);
            // #endif /* LOGGER == ERROR */
        }
    }
}
 
Example 12
Project: otter-G   File: CanalEmbedSelector.java   View Source Code Vote up 5 votes
private void applyWait(int emptyTimes) {
    int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
    if (emptyTimes <= 3) { // 3次以内
        Thread.yield();
    } else { // 超过3次,最多只sleep 10ms
        LockSupport.parkNanos(1000 * 1000L * newEmptyTimes);
    }
}
 
Example 13
Project: otter-G   File: SelectTask.java   View Source Code Vote up 5 votes
public void run() {
    MDC.put(OtterConstants.splitPipelineLogFileKey, String.valueOf(pipelineId));
    try {
        while (running) {
            try {
                if (isStart) {
                    boolean working = arbitrateEventService.mainStemEvent().check(pipelineId);
                    if (!working) {
                        stopup(false);
                    }

                    LockSupport.parkNanos(5 * 1000 * 1000L * 1000L); // 5秒钟检查一次
                } else {
                    startup();
                }
            } catch (Throwable e) {
                if (isInterrupt(e)) {
                    logger.info("INFO ## select is interrupt", e);
                    return;
                } else {
                    logger.warn("WARN ## select is failed.", e);
                    sendRollbackTermin(pipelineId, e);

                    // sleep 10秒再进行重试
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException e1) {
                    }
                }
            }
        }
    } finally {
        arbitrateEventService.mainStemEvent().release(pipelineId);
    }
}
 
Example 14
Project: OpenJSharp   File: LinkedTransferQueue.java   View Source Code Vote up 4 votes
/**
 * Spins/yields/blocks until node s is matched or caller gives up.
 *
 * @param s the waiting node
 * @param pred the predecessor of s, or s itself if it has no
 * predecessor, or null if unknown (the null case does not occur
 * in any current calls but may in possible future extensions)
 * @param e the comparison value for checking match
 * @param timed if true, wait only until timeout elapses
 * @param nanos timeout in nanosecs, used only if timed is true
 * @return matched item, or e if unmatched on interrupt or timeout
 */
private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = -1; // initialized after first item and cancel checks
    ThreadLocalRandom randomYields = null; // bound if needed

    for (;;) {
        Object item = s.item;
        if (item != e) {                  // matched
            // assert item != s;
            s.forgetContents();           // avoid garbage
            return LinkedTransferQueue.<E>cast(item);
        }
        if ((w.isInterrupted() || (timed && nanos <= 0)) &&
                s.casItem(e, s)) {        // cancel
            unsplice(pred, s);
            return e;
        }

        if (spins < 0) {                  // establish spins at/near front
            if ((spins = spinsFor(pred, s.isData)) > 0)
                randomYields = ThreadLocalRandom.current();
        }
        else if (spins > 0) {             // spin
            --spins;
            if (randomYields.nextInt(CHAINED_SPINS) == 0)
                Thread.yield();           // occasionally yield
        }
        else if (s.waiter == null) {
            s.waiter = w;                 // request unpark then recheck
        }
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos > 0L)
                LockSupport.parkNanos(this, nanos);
        }
        else {
            LockSupport.park(this);
        }
    }
}
 
Example 15
Project: openjdk-jdk10   File: LockSupportTest.java   View Source Code Vote up 4 votes
void park(long millis) {
    LockSupport.parkNanos(theBlocker(),
                          MILLISECONDS.toNanos(millis));
}
 
Example 16
Project: googles-monorepo-demo   File: AbstractFuture.java   View Source Code Vote up 4 votes
/**
 * {@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 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 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 SetFuture)) {
      return getDoneValue(localValue);
    }
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    remainingNanos = endNanos - System.nanoTime();
  }
  throw new TimeoutException();
}
 
Example 17
Project: dxram   File: MessageHandler.java   View Source Code Vote up 4 votes
@Override
public void run() {
    int counter = 0;
    long lastSuccessfulPop = 0;
    MessageHeader header;
    Message message;
    MessageReceiver messageReceiver;

    while (!m_shutdown) {
        // #ifdef STATISTICS
        SOP_POP.enter();
        // #endif /* STATISTICS */

        header = m_defaultMessages.popMessageHeader();

        // #ifdef STATISTICS
        SOP_POP.leave();
        // #endif /* STATISTICS */

        if (header == null) {
            if (++counter >= THRESHOLD_TIME_CHECK) {
                if (System.currentTimeMillis() - lastSuccessfulPop > 1000) { // No message header for over a second -> sleep
                    LockSupport.parkNanos(100);
                }
            }

            if (m_overprovisioning) {
                LockSupport.parkNanos(1);
            }

            continue;
        }
        lastSuccessfulPop = System.currentTimeMillis();
        counter = 0;

        // #ifdef STATISTICS
        SOP_CREATE.enter();
        // #endif /* STATISTICS */

        try {
            message = header.createAndFillMessage(m_importers, m_messageHeaderPool);
        } catch (NetworkException e) {
            e.printStackTrace();
            continue;
        }

        // #ifdef STATISTICS
        SOP_CREATE.leave();
        // #endif /* STATISTICS */

        if (message != null) {
            messageReceiver = m_messageReceivers.getReceiver(message.getType(), message.getSubtype());
            if (messageReceiver != null) {
                // #ifdef STATISTICS
                SOP_EXECUTE.enter();
                // #endif /* STATISTICS */

                messageReceiver.onIncomingMessage(message);

                // #ifdef STATISTICS
                SOP_EXECUTE.leave();
                // #endif /* STATISTICS */
            } else {
                // #if LOGGER >= ERROR
                LOGGER.error("No message receiver was registered for %d, %d!", message.getType(), message.getSubtype());
                // #endif /* LOGGER >= ERROR */
            }
        }
    }
}
 
Example 18
Project: dxram   File: LoopbackPipeIn.java   View Source Code Vote up 4 votes
public int read(final ByteBuffer p_buffer) {
    int ret;

    if (m_incomingBufferQueue.isFull()) {
        // Abort to avoid deadlock when sending requests/responses as responses cannot be sent if send thread locks down below
        return 0;
    }

    BufferPool.DirectBufferWrapper directBufferWrapper;
    ByteBuffer buffer;

    directBufferWrapper = m_bufferPool.getBuffer();
    buffer = directBufferWrapper.getBuffer();

    // #ifdef STATISTICS
    COPY.enter();
    // #endif /* STATISTICS */

    if (buffer.remaining() >= p_buffer.remaining()) {
        ret = p_buffer.remaining();
        buffer.put(p_buffer);
    } else {
        ret = buffer.remaining();

        int limit = p_buffer.limit();
        p_buffer.limit(p_buffer.position() + ret);
        buffer.put(p_buffer);
        p_buffer.limit(limit);
    }
    buffer.flip();

    // #ifdef STATISTICS
    COPY.leave();
    // #endif /* STATISTICS */

    // Avoid congestion by not allowing more than m_numberOfBuffers buffers to be cached for reading
    while (!m_incomingBufferQueue.pushBuffer(m_parentConnection, directBufferWrapper, 0, directBufferWrapper.getAddress(), ret)) {
        // #ifdef STATISTICS
        WAITING_FULL.enter();
        // #endif /* STATISTICS */

        LockSupport.parkNanos(100);

        // #ifdef STATISTICS
        WAITING_FULL.leave();
        // #endif /* STATISTICS */
    }

    return ret;
}
 
Example 19
Project: openjdk-jdk10   File: SynchronousQueue.java   View Source Code Vote up 4 votes
/**
 * 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
Project: dble   File: DbleServer.java   View Source Code Vote up 4 votes
public ProxyMetaManager getTmManager() {
    while (metaChanging) {
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
    }
    return tmManager;
}