当前位置: 首页>>代码示例>>Java>>正文


Java LockSupport.parkNanos方法代码示例

本文整理汇总了Java中java.util.concurrent.locks.LockSupport.parkNanos方法的典型用法代码示例。如果您正苦于以下问题:Java LockSupport.parkNanos方法的具体用法?Java LockSupport.parkNanos怎么用?Java LockSupport.parkNanos使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.locks.LockSupport的用法示例。


在下文中一共展示了LockSupport.parkNanos方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: applyWaitMethod

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
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;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:20,代码来源:SleepingWaitStrategy.java

示例2: enterBufferSlot

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:35,代码来源:AbstractPipeIn.java

示例3: run

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
@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());
}
 
开发者ID:firery,项目名称:java-concurrency-cheatsheet,代码行数:17,代码来源:Main.java

示例4: getQueryResult

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
/**
 * 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));
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:34,代码来源:ShowBinlogStatus.java

示例5: compareAndSetRaw

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
private boolean compareAndSetRaw(long offset, long expect, long update) {
    if (unsafe.compareAndSwapLong(array, offset, expect, update)) {
        return true;
    }
    LockSupport.parkNanos(1);
    return false;
}
 
开发者ID:catap,项目名称:atomic,代码行数:8,代码来源:AtomicLongArray.java

示例6: block

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:Phaser.java

示例7: next

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
@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;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:28,代码来源:SingleProducerSequencer.java

示例8: applyWait

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
private static void applyWait(int emptyTimes) throws InterruptedException {
    int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
    if (emptyTimes >= 3) {
        Thread.yield();
        LockSupport.parkNanos(10000 * 1000L * newEmptyTimes);
    }
}
 
开发者ID:zhongchengxcr,项目名称:canal-elasticsearch,代码行数:8,代码来源:LockTest.java

示例9: shouldRetryOnMakeResponseException

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
@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();
}
 
开发者ID:mercadolibre,项目名称:java-restclient,代码行数:29,代码来源:RestClientAsyncRetryTest.java

示例10: awaitDone

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:44,代码来源:FutureTask.java

示例11: run

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
@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 */
        }
    }
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:37,代码来源:MessageCreationCoordinator.java

示例12: applyWait

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:9,代码来源:CanalEmbedSelector.java

示例13: run

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:36,代码来源:SelectTask.java

示例14: awaitMatch

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
/**
 * 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);
        }
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:54,代码来源:LinkedTransferQueue.java

示例15: park

import java.util.concurrent.locks.LockSupport; //导入方法依赖的package包/类
void park(long millis) {
    LockSupport.parkNanos(theBlocker(),
                          MILLISECONDS.toNanos(millis));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:5,代码来源:LockSupportTest.java


注:本文中的java.util.concurrent.locks.LockSupport.parkNanos方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。