Example usage for io.netty.util.internal ThreadLocalRandom current

List of usage examples for io.netty.util.internal ThreadLocalRandom current

Introduction

In this page you can find the example usage for io.netty.util.internal ThreadLocalRandom current.

Prototype

public static ThreadLocalRandom current() 

Source Link

Document

Returns the current thread's ThreadLocalRandom .

Usage

From source file:books.netty.protocol.udp.ChineseProverbServerHandler.java

License:Apache License

private String nextQuote() {
    int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
    return DICTIONARY[quoteId];
}

From source file:com.antsdb.saltedfish.cpp.FishSkipList.java

License:Open Source License

private long doPut(long pKey) {
    int z = 0;//from www.  ja  va  2  s. c  o  m
    outer: for (;;) {
        for (int b = findPredecessor(pKey), n = Node.getNext(this.base, b);;) {
            if (n != 0) {
                int c;
                int f = Node.getNext(this.base, n);
                if (n != Node.getNext(this.base, b)) // inconsistent read
                    break;
                if ((c = compare(pKey, Node.getKeyPointer(this.base, n))) > 0) {
                    b = n;
                    n = f;
                    continue;
                }
                if (c == 0) {
                    return Node.getValuePointer(this.base, n);
                }
                // else c < 0; fall through
            }

            z = Node.alloc(this.heap, pKey, n);
            if (!Node.casNext(this.heap, b, n, z))
                break; // restart if lost race to append to b
            break outer;
        }
    }

    int rnd = ThreadLocalRandom.current().nextInt();
    if ((rnd & 0x80000001) == 0) { // test highest and lowest bits
        int level = 1, max;
        while (((rnd >>>= 1) & 1) != 0)
            ++level;
        int idx = 0;
        int h = getRoot();
        if (level <= (max = HeadIndex.getLevel(this.base, getRoot()))) {
            for (int i = 1; i <= level; ++i)
                idx = IndexNode.alloc(heap, z, idx, 0);
        } else { // try to grow by one level
            level = max + 1; // hold in array and later pick the one to use
            int[] idxs = new int[level + 1];
            for (int i = 1; i <= level; ++i)
                idxs[i] = idx = IndexNode.alloc(heap, z, idx, 0);
            for (;;) {
                h = getRoot();
                int oldLevel = HeadIndex.getLevel(this.base, h);
                if (level <= oldLevel) // lost race to add level
                    break;
                int newh = h;
                int oldbase = IndexNode.getNode(this.base, h);
                for (int j = oldLevel + 1; j <= level; ++j)
                    newh = HeadIndex.alloc(heap, oldbase, newh, idxs[j], j);
                if (casRoot(h, newh)) {
                    h = newh;
                    idx = idxs[level = oldLevel];
                    break;
                }
            }
        }
        // find insertion points and splice in
        splice: for (int insertionLevel = level;;) {
            int j = HeadIndex.getLevel(this.base, h);
            for (int q = h, r = IndexNode.getRight(this.base, q), t = idx;;) {
                if (q == 0 || t == 0)
                    break splice;
                if (r != 0) {
                    int n = IndexNode.getNode(this.base, r);
                    // compare before deletion check avoids needing recheck
                    int c = compare(pKey, Node.getKeyPointer(this.base, n));
                    if (c > 0) {
                        q = r;
                        r = IndexNode.getRight(this.base, r);
                        continue;
                    }
                }

                if (j == insertionLevel) {
                    if (!IndexNode.link(this.base, q, r, t))
                        break; // restart
                    if (--insertionLevel == 0)
                        break splice;
                }

                if (--j >= insertionLevel && j < level)
                    t = IndexNode.getDown(this.base, t);
                q = IndexNode.getDown(this.base, q);
                r = IndexNode.getRight(this.base, q);
            }
        }
    }

    return Node.getValuePointer(this.base, z);
}

From source file:com.antsdb.saltedfish.nosql.Compactor.java

License:Open Source License

@Override
public void run() {
    try {/*from   w  w  w . j a  v a 2  s  .c  o m*/
        List<GTable> tables = new ArrayList<>(humpback.getTables());
        if (tables.size() == 0) {
            return;
        }
        int idx = ThreadLocalRandom.current().nextInt(0, tables.size());
        GTable gtable = tables.get(idx);
        gtable.getMemTable().compact();
    } catch (Exception x) {
        _log.error("", x);
    }
}

From source file:com.bosch.cr.examples.carintegrator.VehicleSimulator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Properties props = new Properties(System.getProperties());
    try {/*from ww  w  .j  av a2  s .  c  o  m*/
        if (new File("config.properties").exists()) {
            props.load(new FileReader("config.properties"));
        } else {
            InputStream i = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("config.properties");
            props.load(i);
            i.close();
        }
        System.out.println("Config: " + props);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    String thingsServiceMessagingUrl = props.getProperty("thingsServiceMessagingUrl");

    String clientId = props.getProperty("clientId");

    URI keystoreUri = new File("CRClient.jks").toURI();
    String keystorePassword = props.getProperty("keyStorePassword");
    String keyAlias = props.getProperty("keyAlias");
    String keyAliasPassword = props.getProperty("keyAliasPassword");

    String proxyHost = props.getProperty("http.proxyHost");
    String proxyPort = props.getProperty("http.proxyPort");

    AuthenticationConfiguration authenticationConfiguration = PublicKeyAuthenticationConfiguration.newBuilder()
            .clientId(clientId).keyStoreLocation(keystoreUri.toURL()).keyStorePassword(keystorePassword)
            .alias(keyAlias).aliasPassword(keyAliasPassword).build();

    TrustStoreConfiguration trustStore = TrustStoreConfiguration.newBuilder()
            .location(VehicleSimulator.class.getResource("/bosch-iot-cloud.jks")).password("jks").build();

    IntegrationClientConfiguration.OptionalConfigSettable configSettable = IntegrationClientConfiguration
            .newBuilder().authenticationConfiguration(authenticationConfiguration)
            .centralRegistryEndpointUrl(thingsServiceMessagingUrl).trustStoreConfiguration(trustStore);
    if (proxyHost != null && proxyPort != null) {
        configSettable = configSettable.proxyConfiguration(ProxyConfiguration.newBuilder().proxyHost(proxyHost)
                .proxyPort(Integer.parseInt(proxyPort)).build());
    }

    IntegrationClient client = IntegrationClientImpl.newInstance(configSettable.build());

    TreeSet<String> activeThings = new TreeSet<>();
    activeThings.addAll(readActiveThings());

    System.out.println("Started...");
    System.out.println("Active things: " + activeThings);

    client.things().registerForThingChanges("lifecycle", change -> {
        if (change.getAction() == ChangeAction.CREATED && change.isFull()) {
            activeThings.add(change.getThingId());
            writeActiveThings(activeThings);
            System.out
                    .println("New thing " + change.getThingId() + " created -> active things: " + activeThings);
        }
    });

    client.subscriptions().create(SubscriptionConsumeOptions.newBuilder().enableConsumeOwnEvents().build())
            .get(10, TimeUnit.SECONDS);
    client.subscriptions().consume().get(10, TimeUnit.SECONDS);

    Thread thread = new Thread(() -> {
        Random random = ThreadLocalRandom.current();
        while (shouldRun) {
            for (String thingId : activeThings) {

                try {
                    Thing thing = client.things().forId(thingId).retrieve(JsonFactory
                            .newFieldSelector("thingId", "features/geolocation/properties/geoposition"))
                            .get(5, TimeUnit.SECONDS);

                    if (!thing.getFeatures().isPresent()
                            || !thing.getFeatures().get().getFeature("geolocation").isPresent()) {
                        System.out.println("Thing " + thingId + " has no Feature \"geolocation\"");
                        return;
                    }

                    JsonObject geolocation = thing.getFeatures().get().getFeature("geolocation")
                            .orElseThrow(RuntimeException::new).getProperties().get();
                    double latitude = geolocation.getValue(JsonFactory.newPointer("geoposition/latitude")).get()
                            .asDouble();
                    double longitude = geolocation.getValue(JsonFactory.newPointer("geoposition/longitude"))
                            .get().asDouble();
                    JsonObject newGeoposition = JsonFactory.newObjectBuilder()
                            .set("latitude", latitude + (random.nextDouble() - 0.5) / 250)
                            .set("longitude", longitude + (random.nextDouble() - 0.5) / 250).build();

                    client.things().forFeature(thingId, "geolocation")
                            .putProperty("geoposition", newGeoposition).get(5, TimeUnit.SECONDS);

                    System.out.print(".");
                    if (random.nextDouble() < 0.01) {
                        System.out.println();
                    }
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    System.out.println("Update thread interrupted");
                    return;
                } catch (ExecutionException | TimeoutException e) {
                    System.out.println("Retrieve thing " + thingId + " failed: " + e);
                }
            }
        }
    });

    thread.start();

    System.out.println("Press enter to terminate");
    System.in.read();

    System.out.println("Shutting down ...");
    shouldRun = false;
    Thread.sleep(5000);
    client.destroy();
    System.out.println("Client destroyed");
}

From source file:com.streamsets.pipeline.lib.parser.net.TestDelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Generates a new pseudo-random integer within the specific range.
 *
 * This is essentially the same method that is present in Apache commons-lang.  It is simply copied here to avoid
 * bringing in a new dependency/*  ww  w. j  ava 2 s  . c  o  m*/
 *
 * @param startInclusive the lowest value that can be generated
 * @param endExclusive
 * @return a pseurandom number in [startInclusive, endExclusive)
 */
private static int nextInt(final int startInclusive, final int endExclusive) {
    if (startInclusive == endExclusive) {
        return startInclusive;
    }

    return startInclusive + ThreadLocalRandom.current().nextInt(endExclusive - startInclusive);
}

From source file:com.zextras.modules.chat.server.events.EventId.java

License:Open Source License

public static EventId randomUUID() {
    byte[] randombytes = new byte[3];
    ThreadLocalRandom random = ThreadLocalRandom.current();
    random.nextBytes(randombytes);/* www .ja v a  2  s. c  o m*/
    return new EventId(FastBase64.encodeToString(randombytes, false));
}

From source file:divconq.http.multipart.HttpPostRequestEncoder.java

License:Apache License

/**
 *
 * @return a newly generated Delimiter (either for DATA or MIXED)
 *//*from  w  w  w.  java2 s .  co  m*/
private static String getNewMultipartDelimiter() {
    // construct a generated delimiter
    return Long.toHexString(ThreadLocalRandom.current().nextLong()).toLowerCase();
}

From source file:io.mandrel.requests.dns.DNSNameResolver.java

License:Apache License

public InetAddress resolve(String name) throws UnknownHostException {
    InetSocketAddress unresolved = InetSocketAddress.createUnresolved(name,
            ThreadLocalRandom.current().nextInt(65536));
    try {/*from ww w. j av  a 2  s  .  c o m*/
        return resolver.resolve(unresolved).get().getAddress();
    } catch (InterruptedException | ExecutionException e) {
        UnknownHostException unknownHostException = new UnknownHostException(name);
        unknownHostException.setStackTrace(e.getStackTrace());
        throw unknownHostException;
    }
}

From source file:io.reactivesocket.transport.tcp.Pong.java

License:Apache License

public static void main(String... args) throws Exception {
    byte[] response = new byte[1024];
    ThreadLocalRandom.current().nextBytes(response);

    TcpReactiveSocketServer.create(7878).start((setupPayload, reactiveSocket) -> {
        return new RequestHandler.Builder().withRequestResponse(payload -> {
            Payload responsePayload = new Payload() {
                ByteBuffer data = ByteBuffer.wrap(response);
                ByteBuffer metadata = ByteBuffer.allocate(0);

                @Override/*from ww  w  .  j  a v a  2 s .c  om*/
                public ByteBuffer getData() {
                    return data;
                }

                @Override
                public ByteBuffer getMetadata() {
                    return metadata;
                }
            };
            return RxReactiveStreams.toPublisher(Observable.just(responsePayload));
        }).build();
    }).awaitShutdown();
}

From source file:io.vertx.core.dns.impl.fix.DnsQueryContextManager.java

License:Apache License

int add(DnsQueryContext qCtx) {
    final IntObjectMap<DnsQueryContext> contexts = getOrCreateContextMap(qCtx.nameServerAddr());

    int id = ThreadLocalRandom.current().nextInt(1, 65536);
    final int maxTries = 65535 << 1;
    int tries = 0;

    synchronized (contexts) {
        for (;;) {
            if (!contexts.containsKey(id)) {
                contexts.put(id, qCtx);/*  w w  w  .j  av a2s .co m*/
                return id;
            }

            id = id + 1 & 0xFFFF;

            if (++tries >= maxTries) {
                throw new IllegalStateException("query ID space exhausted: " + qCtx.question());
            }
        }
    }
}