Java Sleep sleepUpTo(final long millis)

Here you can find the source of sleepUpTo(final long millis)

Description

Method to add a random delay or if none to yeild to give any waiting threads a chance This helps make test threaded code more random to track synchronized issues

License

Apache License

Parameter

Parameter Description
millis up to the many ms

Return

actual sleep time

Declaration

public final static int sleepUpTo(final long millis) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/* w w w.ja v a 2  s  .  co  m*/
     * Method to add a random delay or if none to yeild to give any waiting threads a chance This helps make test threaded code more random to track
     * synchronized issues
     * 
     * @param millis
     *            up to the many ms
     * @return actual sleep time
     */
    public final static int sleepUpTo(final long millis) {
        try {
            if (millis > 0) {
                int realSleep = (int) Math.floor(Math.random() * (millis + 1));
                if (realSleep > 0) {
                    Thread.sleep(realSleep);
                    return realSleep;
                } else {
                    // Give any waiting threads a go
                    Thread.yield();
                    return 0;
                }
            }
        } catch (final InterruptedException e) {
            // It's not an error that we were Interrupted !! don't log the
            // exception !
            return -1;
        }
        return 0;
    }

    public final static boolean sleep(final long millis) {
        try {
            if (millis > 0) {
                Thread.sleep(millis);
            }
        } catch (final InterruptedException e) {
            // It's not an error that we were Interrupted !! don't log the
            // exception !
            return false;
        }

        return true;
    }

    public final static boolean sleep(final Long millis) {
        if (millis != null) {
            return sleep(millis.longValue());
        }
        return true;
    }
}

Related

  1. sleepTight(final long millis)
  2. sleepUninterruptedly(long millis)
  3. sleepUninterruptibly(long msecs)
  4. sleepUntil(long time)
  5. sleepUntil(long timestamp)
  6. sleepWithoutInterrupt(final long msToWait)
  7. sleepWithoutInterruptions(long milliseconds)
  8. sleepyMillis(long millis)