Example usage for java.util.concurrent.locks LockSupport parkNanos

List of usage examples for java.util.concurrent.locks LockSupport parkNanos

Introduction

In this page you can find the example usage for java.util.concurrent.locks LockSupport parkNanos.

Prototype

public static void parkNanos(long nanos) 

Source Link

Document

Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.

Usage

From source file:org.apache.nifi.controller.scheduling.TestProcessorLifecycle.java

/**
 * Concurrency test that is basically hammers on both stop and start
 * operation validating their idempotency.
 *///from  ww  w.  j  a va2 s  .  com
@Test
@Ignore
public void validateLifecycleOperationOrderWithConcurrentCallsToStartStop() throws Exception {
    fc = this.buildFlowControllerForTest();
    ProcessGroup testGroup = fc.createProcessGroup(UUID.randomUUID().toString());
    this.setControllerRootGroup(fc, testGroup);
    final ProcessorNode testProcNode = fc.createProcessor(TestProcessor.class.getName(),
            UUID.randomUUID().toString());
    testProcNode.setProperties(properties);
    TestProcessor testProcessor = (TestProcessor) testProcNode.getProcessor();

    // sets the scenario for the processor to run
    this.noop(testProcessor);

    final ProcessScheduler ps = fc.getProcessScheduler();
    ExecutorService executor = Executors.newFixedThreadPool(100);
    int startCallsCount = 10000;
    final CountDownLatch countDownCounter = new CountDownLatch(startCallsCount);
    assertTrue(testProcNode.getScheduledState() == ScheduledState.STOPPED);
    final Random random = new Random();
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                ps.stopProcessor(testProcNode);
                countDownCounter.countDown();
            }
        });
    }
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                ps.startProcessor(testProcNode);
                countDownCounter.countDown();
            }
        });
    }
    assertTrue(countDownCounter.await(1000000, TimeUnit.MILLISECONDS));
    String previousOperation = null;
    for (String operationName : testProcessor.operationNames) {
        if (previousOperation == null || previousOperation.equals("@OnStopped")) {
            assertEquals("@OnScheduled", operationName);
        } else if (previousOperation.equals("@OnScheduled")) {
            assertEquals("@OnUnscheduled", operationName);
        } else if (previousOperation.equals("@OnUnscheduled")) {
            assertTrue(operationName.equals("@OnStopped") || operationName.equals("@OnScheduled"));
        }
        previousOperation = operationName;
    }
    executor.shutdownNow();
}

From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java

@Test(timeout = 20000)
public void validateContainerLaunchWithVariableLengthCommandsUntillDone() throws Exception {
    ClassPathResource resource = new ClassPathResource("variable", this.getClass());
    YarnApplication<Void> yarnApplication = YarnAssembly
            .forApplicationContainer(resource.getFile().getAbsolutePath()).containerCount(6)
            .withApplicationMaster().build("sample-yarn-application");

    assertEquals(0, yarnApplication.liveContainers());
    assertFalse(yarnApplication.isRunning());
    yarnApplication.launch();/*from w  ww .  j  av  a  2  s  . c  o m*/
    while (yarnApplication.isRunning()) {
        LockSupport.parkNanos(1000000);
    }
    assertFalse(yarnApplication.isRunning());
}

From source file:org.apache.nifi.controller.scheduling.ProcessorLifecycleIT.java

/**
 * Concurrency test that is basically hammers on both stop and start
 * operation validating their idempotency.
 */// ww w.  j a v a2s .  c  o m
@Test
@Ignore
public void validateLifecycleOperationOrderWithConcurrentCallsToStartStop() throws Exception {
    final FlowManagerAndSystemBundle fcsb = this.buildFlowControllerForTest();
    flowManager = fcsb.getFlowManager();

    ProcessGroup testGroup = flowManager.createProcessGroup(UUID.randomUUID().toString());
    final ProcessorNode testProcNode = flowManager.createProcessor(TestProcessor.class.getName(),
            UUID.randomUUID().toString(), fcsb.getSystemBundle().getBundleDetails().getCoordinate());
    testProcNode.setProperties(properties);
    TestProcessor testProcessor = (TestProcessor) testProcNode.getProcessor();

    // sets the scenario for the processor to run
    this.noop(testProcessor);

    ExecutorService executor = Executors.newFixedThreadPool(100);
    int startCallsCount = 10000;
    final CountDownLatch countDownCounter = new CountDownLatch(startCallsCount);
    assertCondition(() -> ScheduledState.STOPPED == testProcNode.getScheduledState());
    final Random random = new Random();
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                processScheduler.stopProcessor(testProcNode);
                countDownCounter.countDown();
            }
        });
    }
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                processScheduler.startProcessor(testProcNode, true);
                countDownCounter.countDown();
            }
        });
    }
    assertTrue(countDownCounter.await(1000000, TimeUnit.MILLISECONDS));
    String previousOperation = null;
    for (String operationName : testProcessor.operationNames) {
        if (previousOperation == null || previousOperation.equals("@OnStopped")) {
            assertEquals("@OnScheduled", operationName);
        } else if (previousOperation.equals("@OnScheduled")) {
            assertEquals("@OnUnscheduled", operationName);
        } else if (previousOperation.equals("@OnUnscheduled")) {
            assertTrue(operationName.equals("@OnStopped") || operationName.equals("@OnScheduled"));
        }
        previousOperation = operationName;
    }
    executor.shutdownNow();
}

From source file:LinkedTransferQueue.java

/**
 * Spins/blocks until node s is fulfilled or caller gives up,
 * depending on wait mode.//w  w w .  j  ava 2s . c  o  m
 *
 * @param pred the predecessor of waiting node
 * @param s the waiting node
 * @param e the comparison value for checking match
 * @param mode mode
 * @param nanos timeout value
 * @return matched item, or s if cancelled
 */
private Object awaitFulfill(QNode pred, QNode s, Object e, int mode, long nanos) {
    if (mode == NOWAIT) {
        return null;
    }

    long lastTime = mode == TIMEOUT ? System.nanoTime() : 0;
    Thread w = Thread.currentThread();
    int spins = -1; // set to desired spin count below
    for (;;) {
        if (w.isInterrupted()) {
            s.compareAndSet(e, s);
        }
        Object x = s.get();
        if (x != e) { // Node was matched or cancelled
            advanceHead(pred, s); // unlink if head
            if (x == s) { // was cancelled
                clean(pred, s);
                return null;
            } else if (x != null) {
                s.set(s); // avoid garbage retention
                return x;
            } else {
                return e;
            }
        }
        if (mode == TIMEOUT) {
            long now = System.nanoTime();
            nanos -= now - lastTime;
            lastTime = now;
            if (nanos <= 0) {
                s.compareAndSet(e, s); // try to cancel
                continue;
            }
        }
        if (spins < 0) {
            QNode h = this.head.get(); // only spin if at head
            spins = h != null && h.next == s ? (mode == TIMEOUT ? maxTimedSpins : maxUntimedSpins) : 0;
        }
        if (spins > 0) {
            --spins;
        } else if (s.waiter == null) {
            s.waiter = w;
        } else if (mode != TIMEOUT) {
            //                LockSupport.park(this);
            LockSupport.park(); // allows run on java5
            s.waiter = null;
            spins = -1;
        } else if (nanos > spinForTimeoutThreshold) {
            //                LockSupport.parkNanos(this, nanos);
            LockSupport.parkNanos(nanos);
            s.waiter = null;
            spins = -1;
        }
    }
}

From source file:com.hazelcast.stabilizer.Utils.java

public static void sleepNanos(long nanos) {
    if (nanos <= 0) {
        return;/*from  w w w  .java2 s .c  om*/
    }

    LockSupport.parkNanos(nanos);
}

From source file:com.alibaba.otter.node.etl.select.selector.canal.CanalEmbedSelector.java

private void applyWait(int emptyTimes) {
    int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
    if (emptyTimes <= 3) { // 3
        Thread.yield();/* www  .  j a v a  2 s .c o m*/
    } else { // 3?sleep 10ms
        LockSupport.parkNanos(1000 * 1000L * newEmptyTimes);
    }
}

From source file:cx.fbn.nevernote.threads.IndexRunner.java

private void waitSeconds(int len) {
    long starttime = 0; // variable declared
    //...// ww  w  .ja  va2  s . c  o m
    // for the first time, remember the timestamp
    starttime = System.currentTimeMillis();
    // the next timestamp we want to wake up
    starttime += (1000.0);
    // Wait until the desired next time arrives using nanosecond
    // accuracy timer (wait(time) isn't accurate enough on most platforms) 
    LockSupport.parkNanos((Math.max(0, starttime - System.currentTimeMillis()) * 1000000));
}

From source file:com.yahoo.ycsb.db.couchbase2.Couchbase2Client.java

@Override
public int calculateStrategy(final IntSupplier supplier, final boolean hasTasks) throws Exception {
    int selectNowResult = supplier.get();
    if (hasTasks || selectNowResult != 0) {
        counter = 0;/*from w w w . ja v  a  2s. c  om*/
        return selectNowResult;
    }
    counter++;

    if (counter > 2000) {
        LockSupport.parkNanos(1);
    } else if (counter > 3000) {
        Thread.yield();
    } else if (counter > 4000) {
        LockSupport.parkNanos(1000);
    } else if (counter > 5000) {
        // defer to blocking select
        counter = 0;
        return SelectStrategy.SELECT;
    }

    return SelectStrategy.CONTINUE;
}