Java Sleep sleepNanos(final long nanoDuration)

Here you can find the source of sleepNanos(final long nanoDuration)

Description

Sleeps for specified amount of time in nanoseconds.

License

Apache License

Parameter

Parameter Description
nanoDuration the amount of nanoseconds to wait

Exception

Parameter Description
InterruptedException if the current thread gets interrupted

Declaration

public static void sleepNanos(final long nanoDuration) throws InterruptedException 

Method Source Code

//package com.java2s;
/*//  w w w .j  a va 2 s.com
 * Copyright 2018 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    private static final long SLEEP_PRECISION = Long.valueOf(System.getProperty("TIMER_SLEEP_PRECISION", "50000"));
    private static final long SPIN_YIELD_PRECISION = Long
            .valueOf(System.getProperty("TIMER_YIELD_PRECISION", "30000"));

    /**
     * Sleeps for specified amount of time in nanoseconds.
     * @param nanoDuration the amount of nanoseconds to wait
     * @throws InterruptedException if the current thread gets interrupted
     */
    public static void sleepNanos(final long nanoDuration) throws InterruptedException {
        final long end = System.nanoTime() + nanoDuration;
        long timeLeft = nanoDuration;
        do {
            if (timeLeft > SLEEP_PRECISION) {
                Thread.sleep(1);
            } else if (timeLeft > SPIN_YIELD_PRECISION) {
                Thread.yield();
            }
            timeLeft = end - System.nanoTime();
        } while (timeLeft > 0);
    }
}

Related

  1. sleepMillis(long millis)
  2. sleepMilliseconds(long ms)
  3. sleepMilliseconds(long ms)
  4. sleepMs(final int millis)
  5. sleepMSInChunks(long ms)
  6. sleepNanos(long nanoseconds)
  7. sleepNoException(int ms)
  8. sleepNoShit(long nanos)
  9. sleepNotException(long millis)