Example usage for java.util.concurrent ThreadLocalRandom current

List of usage examples for java.util.concurrent ThreadLocalRandom current

Introduction

In this page you can find the example usage for java.util.concurrent ThreadLocalRandom current.

Prototype

public static ThreadLocalRandom current() 

Source Link

Document

Returns the current thread's ThreadLocalRandom .

Usage

From source file:org.jahia.test.services.acl.AclExtendedNodesPerformanceTest.java

private void touchRandomFilesByRandomUsers(final String workspace,
        ListMultimap<Integer, String> filePathsByOwner, final Collection<Long> touchSamples) {

    List<String> filePathsToTouch = new LinkedList<String>();
    Random random = ThreadLocalRandom.current();
    final Set<Integer> ownersSeen = new HashSet<Integer>();
    for (int numOwners = 0; numOwners < NUM_OWNER_USERS;) {
        int ownerIndex = random.nextInt(NUM_USERS);
        if (ownersSeen.contains(ownerIndex)) {
            continue;
        }/*from  w  ww . j a v a  2  s .  c o  m*/
        ownersSeen.add(ownerIndex);
        numOwners++;
        List<String> filePaths = filePathsByOwner.get(ownerIndex);
        filePathsToTouch
                .addAll(PerformanceTestUtils.getUniqueRandomElements(filePaths, NUM_FILES_TO_TOUCH_PER_OWNER));
    }
    final List<String> finalFilePathsToTouch = new ArrayList<String>(filePathsToTouch);

    accessFilesByRandomUsers(workspace, NUM_TOUCHING_USERS, new UserRejector() {

        @Override
        public boolean isToBeRejected(int userIndex) {
            // Reject this touching user in case it is among owners of files to touch.
            return ownersSeen.contains(userIndex);
        }
    }, new FilesAccessor() {

        @Override
        public void accessFilesByUser(int touchingIndex) {
            JCRUserNode touchingUser = getUser(touchingIndex);
            accessFiles(workspace, touchingUser, finalFilePathsToTouch, touchSamples, new TouchFileProcessor());
        }
    });
}

From source file:org.apache.hadoop.hbase.ipc.BlockingRpcConnection.java

/**
 * If multiple clients with the same principal try to connect to the same server at the same time,
 * the server assumes a replay attack is in progress. This is a feature of kerberos. In order to
 * work around this, what is done is that the client backs off randomly and tries to initiate the
 * connection again. The other problem is to do with ticket expiry. To handle that, a relogin is
 * attempted./*ww  w.j a  va 2s. c  om*/
 * <p>
 * The retry logic is governed by the {@link #shouldAuthenticateOverKrb} method. In case when the
 * user doesn't have valid credentials, we don't need to retry (from cache or ticket). In such
 * cases, it is prudent to throw a runtime exception when we receive a SaslException from the
 * underlying authentication implementation, so there is no retry from other high level (for eg,
 * HCM or HBaseAdmin).
 * </p>
 */
private void handleSaslConnectionFailure(final int currRetries, final int maxRetries, final Exception ex,
        final UserGroupInformation user) throws IOException, InterruptedException {
    closeSocket();
    user.doAs(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws IOException, InterruptedException {
            if (shouldAuthenticateOverKrb()) {
                if (currRetries < maxRetries) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Exception encountered while connecting to " + "the server : " + ex);
                    }
                    // try re-login
                    relogin();
                    disposeSasl();
                    // have granularity of milliseconds
                    // we are sleeping with the Connection lock held but since this
                    // connection instance is being used for connecting to the server
                    // in question, it is okay
                    Thread.sleep(ThreadLocalRandom.current().nextInt(reloginMaxBackoff) + 1);
                    return null;
                } else {
                    String msg = "Couldn't setup connection for "
                            + UserGroupInformation.getLoginUser().getUserName() + " to " + serverPrincipal;
                    LOG.warn(msg, ex);
                    throw (IOException) new IOException(msg).initCause(ex);
                }
            } else {
                LOG.warn("Exception encountered while connecting to " + "the server : " + ex);
            }
            if (ex instanceof RemoteException) {
                throw (RemoteException) ex;
            }
            if (ex instanceof SaslException) {
                String msg = "SASL authentication failed."
                        + " The most likely cause is missing or invalid credentials." + " Consider 'kinit'.";
                LOG.fatal(msg, ex);
                throw new RuntimeException(msg, ex);
            }
            throw new IOException(ex);
        }
    });
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("a pseudo-random value")
@ScalarFunction(alias = "rand", deterministic = false)
@SqlType(StandardTypes.DOUBLE)/* w w  w .jav  a 2 s .c om*/
public static double random() {
    return ThreadLocalRandom.current().nextDouble();
}

From source file:org.jahia.test.services.acl.AclExtendedNodesPerformanceTest.java

private void downloadRandomFilesByRandomUsers(final String workspace,
        final ListMultimap<Integer, String> filePathsByOwner, final Collection<Long> downloadSamples) {

    final NodeProcessor fileDownloader = new DownloadFileProcessor();
    final Set<String> filePathsSeen = new HashSet<String>();

    accessFilesByRandomUsers(workspace, NUM_DOWNLOADER_USERS, null, new FilesAccessor() {

        @Override/*from w w w . j  a  v a2s .  c  o m*/
        public void accessFilesByUser(int downloaderIndex) {
            JCRUserNode downloaderUser = getUser(downloaderIndex);
            Random random = ThreadLocalRandom.current();
            final Set<Integer> ownersSeen = new HashSet<Integer>();
            for (int numOwners = 0; numOwners < NUM_OWNER_USERS;) {
                int ownerIndex = random.nextInt(NUM_USERS);
                if (ownersSeen.contains(ownerIndex)) {
                    continue;
                }
                if (ownerIndex == downloaderIndex) {
                    continue;
                }
                ownersSeen.add(ownerIndex);
                numOwners++;
                List<String> filePaths = filePathsByOwner.get(ownerIndex);
                Collection<String> filePathsToDownload = PerformanceTestUtils.getUniqueRandomElements(filePaths,
                        NUM_FILES_TO_DOWNLOAD_PER_DOWNLOADER_PER_OWNER,
                        new PerformanceTestUtils.ElementRejector<String>() {

                            @Override
                            public boolean isToBeRejected(String filePath) {
                                return filePathsSeen.contains(filePath);
                            }
                        });
                filePathsSeen.addAll(filePathsToDownload);
                accessFiles(workspace, downloaderUser, filePathsToDownload, downloadSamples, fileDownloader);
            }
        }
    });
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("a pseudo-random number between 0 and value (exclusive)")
@ScalarFunction(value = "random", alias = "rand", deterministic = false)
@SqlType(StandardTypes.TINYINT)/*from w  w  w .  j  av  a 2 s. c  o  m*/
public static long randomTinyint(@SqlType(StandardTypes.TINYINT) long value) {
    checkCondition(value > 0, INVALID_FUNCTION_ARGUMENT, "bound must be positive");
    return ThreadLocalRandom.current().nextInt((int) value);
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("a pseudo-random number between 0 and value (exclusive)")
@ScalarFunction(value = "random", alias = "rand", deterministic = false)
@SqlType(StandardTypes.SMALLINT)//from ww  w  .j a va  2  s  . c  o m
public static long randomSmallint(@SqlType(StandardTypes.SMALLINT) long value) {
    checkCondition(value > 0, INVALID_FUNCTION_ARGUMENT, "bound must be positive");
    return ThreadLocalRandom.current().nextInt((int) value);
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("a pseudo-random number between 0 and value (exclusive)")
@ScalarFunction(value = "random", alias = "rand", deterministic = false)
@SqlType(StandardTypes.INTEGER)//from   ww  w  .  ja  v a  2 s.co  m
public static long randomInteger(@SqlType(StandardTypes.INTEGER) long value) {
    checkCondition(value > 0, INVALID_FUNCTION_ARGUMENT, "bound must be positive");
    return ThreadLocalRandom.current().nextInt((int) value);
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("a pseudo-random number between 0 and value (exclusive)")
@ScalarFunction(alias = "rand", deterministic = false)
@SqlType(StandardTypes.BIGINT)/*from ww  w  .  ja v  a  2s.c  o  m*/
public static long random(@SqlType(StandardTypes.BIGINT) long value) {
    checkCondition(value > 0, INVALID_FUNCTION_ARGUMENT, "bound must be positive");
    return ThreadLocalRandom.current().nextLong(value);
}

From source file:org.apache.jmeter.services.FileServer.java

/**
 * Method will get a random file in a base directory 
 * <p>/*from   ww w. j  a  v  a 2  s .c  o m*/
 * TODO hey, not sure this
 * method belongs here. FileServer is for threadsafe File access relative to
 * current test's base directory.
 *
 * @param basedir
 *            name of the directory in which the files can be found
 * @param extensions
 *            array of allowed extensions, if <code>null</code> is given,
 *            any file be allowed
 * @return a random File from the <code>basedir</code> that matches one of
 *         the extensions
 */
public File getRandomFile(String basedir, String[] extensions) {
    File input = null;
    if (basedir != null) {
        File src = new File(basedir);
        File[] lfiles = src.listFiles(new JMeterFileFilter(extensions));
        if (lfiles != null) {
            // lfiles cannot be null as it has been checked before
            int count = lfiles.length;
            input = lfiles[ThreadLocalRandom.current().nextInt(count)];
        }
    }
    return input;
}

From source file:org.jahia.test.services.acl.AclExtendedNodesPerformanceTest.java

private void accessFilesByRandomUsers(String workspace, int numAccessorUsers, UserRejector userRejector,
        FilesAccessor fileAccessor) {/*from  w w w . j  av  a 2  s  .com*/
    Random random = ThreadLocalRandom.current();
    Set<Integer> accessorsSeen = new HashSet<Integer>();
    for (int numAccessors = 0; numAccessors < numAccessorUsers;) {
        int accessorIndex = random.nextInt(NUM_USERS);
        if (accessorsSeen.contains(accessorIndex)) {
            continue;
        }
        if (userRejector != null && userRejector.isToBeRejected(accessorIndex)) {
            continue;
        }
        accessorsSeen.add(accessorIndex);
        numAccessors++;
        fileAccessor.accessFilesByUser(accessorIndex);
    }
}