Java Thread Lock sleepRandomNanos(Random random, long maxDelayNanos)

Here you can find the source of sleepRandomNanos(Random random, long maxDelayNanos)

Description

Sleeps a random amount of time.

License

Open Source License

Parameter

Parameter Description
random the Random used to randomize
maxDelayNanos the maximum sleeping period in nano seconds. If maxDelayNanos equals or smaller than zero, the call is ignored.

Declaration

public static void sleepRandomNanos(Random random, long maxDelayNanos) 

Method Source Code

//package com.java2s;
/*/*  ww w .ja v  a2s .c  o m*/
 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
 *
 * 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.
 */

import java.util.Random;

import java.util.concurrent.locks.LockSupport;

public class Main {
    /**
     * Sleeps a random amount of time.
     *
     * @param random        the Random used to randomize
     * @param maxDelayNanos the maximum sleeping period in nano seconds. If maxDelayNanos equals or smaller than zero,
     *                      the call is ignored.
     */
    public static void sleepRandomNanos(Random random, long maxDelayNanos) {
        if (maxDelayNanos <= 0) {
            return;
        }

        long randomValue = Math.abs(random.nextLong());
        long delayNanos = randomValue % maxDelayNanos;
        LockSupport.parkNanos(delayNanos);
    }
}

Related

  1. release()
  2. releaseLock(final Lock lock)
  3. releaseReadLock(final ReadWriteLock lock)
  4. runSync(final Lock lock, final Runnable task)
  5. sleepNanos(long nanos)