List of usage examples for java.util.concurrent ThreadLocalRandom current
public static ThreadLocalRandom current()
From source file:Test.java
public static void main(String[] args) { System.out.println("Five random integers"); for (int i = 0; i < 5; i++) { System.out.println(ThreadLocalRandom.current().nextInt()); }/*from w w w . j a va 2s. c o m*/ System.out.println("Random double number between 0.0 and 35.0"); System.out.println(ThreadLocalRandom.current().nextDouble(35.0)); System.out.println("Five random Long numbers between 1234567 and 7654321"); for (int i = 0; i < 5; i++) { System.out.println(ThreadLocalRandom.current().nextLong(1234567L, 7654321L)); } }
From source file:Main.java
public static void main(String[] args) throws Exception { ExecutorService ex = Executors.newSingleThreadExecutor(); Future<Integer> future = // This Lambda evaluated to Callable<Integer> ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10)); System.out.println("Randomized value: " + future.get()); }
From source file:Main.java
public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService ex = Executors.newSingleThreadExecutor(); Future<Integer> future = // This Lambda evaluated to Callable<Integer> ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10)); System.out.println("Randomized value: " + future.get()); }
From source file:com.test.zmisc.App.java
public static void main(String[] args) { double[] a = new double[32768]; double[] b = new double[32768]; ThreadLocalRandom rand = ThreadLocalRandom.current(); for (int i = 0; i < a.length; i++) { a[i] = rand.nextDouble();// ww w . j a v a2 s .c o m b[i] = a[i]; } long ts = System.currentTimeMillis(); PearsonsCorrelation corr = new PearsonsCorrelation(); corr.correlation(a, b); ts = System.currentTimeMillis() - ts; System.out.println("Time elapsed:" + ts + "ms"); // standard deviation is the sqrt(mean((X-avg)^2)) ts = System.currentTimeMillis(); double amean = average(a); double aStdDev = standardDeviation(a, amean); StandardDeviation sd = new StandardDeviation(); sd.setBiasCorrected(false); double bmean = average(b); double bStdDev = standardDeviation(b, bmean); double cor = (covariance(a, aStdDev, b, bmean)) / (aStdDev * bStdDev); ts = System.currentTimeMillis() - ts; System.out.println("Time elapsed:" + ts + "ms"); }
From source file:org.apache.druid.query.aggregation.datasketches.quantiles.GenerateTestData.java
public static void main(String[] args) throws Exception { Path buildPath = FileSystems.getDefault().getPath("doubles_build_data.tsv"); Path sketchPath = FileSystems.getDefault().getPath("doubles_sketch_data.tsv"); BufferedWriter buildData = Files.newBufferedWriter(buildPath, StandardCharsets.UTF_8); BufferedWriter sketchData = Files.newBufferedWriter(sketchPath, StandardCharsets.UTF_8); Random rand = ThreadLocalRandom.current(); int sequenceNumber = 0; for (int i = 0; i < 20; i++) { int product = rand.nextInt(10); UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build(); for (int j = 0; j < 20; j++) { double value = rand.nextDouble(); buildData.write("2016010101"); buildData.write('\t'); buildData.write(Integer.toString(sequenceNumber)); // dimension with unique numbers for ingesting raw data buildData.write('\t'); buildData.write(Integer.toString(product)); // product dimension buildData.write('\t'); buildData.write(Double.toString(value)); buildData.newLine();//from www. j ava 2 s . com sketch.update(value); sequenceNumber++; } sketchData.write("2016010101"); sketchData.write('\t'); sketchData.write(Integer.toString(product)); // product dimension sketchData.write('\t'); sketchData.write(Base64.encodeBase64String(sketch.toByteArray(true))); sketchData.newLine(); } buildData.close(); sketchData.close(); }
From source file:cf.service.integration.FunctionalTest.java
public static void main(String[] args) throws Exception { final CfTokens cfTokens = new CfTokens(); final CfTokens.CfToken target = cfTokens.getCurrentTargetToken(); if (target == null) { System.err.println("It appears you haven't logged into a Cloud Foundry instance with cf."); return;//from w w w . j av a2 s .c o m } if (target.getVersion() == null || target.getVersion() != 2) { System.err.println("You must target a v2 Cloud Controller using cf."); return; } if (target.getSpaceGuid() == null) { System.err.println("You must select a space to use using cf."); return; } LOGGER.info("Using Cloud Controller at: {}", target.getTarget()); final String label = "testService" + ThreadLocalRandom.current().nextInt(); final String provider = "core"; final URI url = URI.create("http://" + localIp(target.getTarget()) + ":" + serverPort); final String description = "A service used for testing the service framework."; final String version = "0.1"; final String servicePlan = "ServicePlan"; final String servicePlanDescription = "Finest service... ever."; final String authToken = "SsshhhThisIsASecret"; final CloudController cloudControllerClient = new DefaultCloudController(new DefaultHttpClient(), target.getTarget()); try (final SimpleHttpServer server = new SimpleHttpServer(new InetSocketAddress(serverPort))) { final UUID serviceGuid = cloudControllerClient.createService(target.getToken(), new Service(label, provider, url, description, version, null, true, null)); LOGGER.debug("Created service with guid: {}", serviceGuid); final TestProvisioner provisioner = new TestProvisioner(); new NettyBrokerServer(server, provisioner, authToken); try { final UUID servicePlanGuid = cloudControllerClient.createServicePlan(target.getToken(), new ServicePlan(servicePlan, servicePlanDescription, serviceGuid, true, null)); LOGGER.debug("Created service plan with guid: {}", serviceGuid); final UUID authTokenGuid = cloudControllerClient.createAuthToken(target.getToken(), new ServiceAuthToken(label, provider, authToken)); LOGGER.debug("Created service token with guid: {}", authTokenGuid); try { final String instanceName = "myservice"; final UUID serviceInstanceGuid = cloudControllerClient.createServiceInstance(target.getToken(), instanceName, servicePlanGuid, target.getSpaceGuid()); int instanceId = -1; try { assertEquals(1, provisioner.getCreateInvocationCount()); instanceId = provisioner.getLastCreateId(); } finally { cloudControllerClient.deleteServiceInstance(target.getToken(), serviceInstanceGuid); assertEquals(provisioner.getDeleteInvocationCount(), 1); assertEquals(provisioner.getLastDeleteId(), instanceId); } } finally { cloudControllerClient.deleteServiceAuthToken(target.getToken(), authTokenGuid); } } finally { cloudControllerClient.deleteService(target.getToken(), serviceGuid); } } // TODO: Create service pointing to test gateway // TODO: Create service instance and validate }
From source file:org.wso2.carbon.sample.isanalyticsclient.Client.java
public static void main(String[] args) { DataPublisherUtil.setKeyStoreParams(); DataPublisherUtil.setTrustStoreParams(); log.info("These are the provided configurations: " + Arrays.deepToString(args)); String protocol = args[0];//from ww w. java2 s . c o m String host = args[1]; String port = args[2]; int sslPort = Integer.parseInt(port) + 100; String username = args[3]; String password = args[4]; String numberOfEventsStr = args[5]; int numberOfEvents = Integer.parseInt(numberOfEventsStr); int metaTenantIdMinBound = 1000; int metaTenantIdMaxBound = 9999; try { log.info("Starting IS Analytics Event Client"); AgentHolder.setConfigPath(DataPublisherUtil.getDataAgentConfigPath(agentConfigFileName)); DataPublisher dataPublisher = new DataPublisher(protocol, "tcp://" + host + ":" + port, "ssl://" + host + ":" + sslPort, username, password); Event authEvent = new Event(); authEvent.setStreamId(DataBridgeCommonsUtils.generateStreamId(STREAM_NAME, VERSION)); authEvent.setCorrelationData(null); Event sessionEvent = new Event(); sessionEvent.setStreamId(DataBridgeCommonsUtils.generateStreamId(SESSION_STREAM_NAME, VERSION)); for (int i = 0; i < numberOfEvents; i++) { int metaTenantId = ThreadLocalRandom.current().nextInt(metaTenantIdMinBound, metaTenantIdMaxBound); Object[] data = getEventDataObject(); authEvent.setMetaData(new Object[] { metaTenantId }); authEvent.setPayloadData(data); Object[] sessionData = getEventDataObjectForSession(data); sessionEvent.setMetaData(new Object[] { metaTenantId }); sessionEvent.setPayloadData(sessionData); dataPublisher.publish(authEvent); dataPublisher.publish(sessionEvent); } try { Thread.sleep(5000); } catch (InterruptedException e) { log.error(e); } dataPublisher.shutdown(); log.info("Events published successfully"); } catch (Throwable e) { log.error(e); } }
From source file:squash.tools.FakeBookingCreator.java
public static void main(String[] args) throws IOException { int numberOfDays = 21; int numberOfCourts = 5; int maxCourtSpan = 5; int numberOfSlots = 16; int maxSlotSpan = 3; int minSurnameLength = 2; int maxSurnameLength = 20; int minBookingsPerDay = 0; int maxBookingsPerDay = 8; LocalDate startDate = LocalDate.of(2016, 7, 5); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List<Booking> bookings = new ArrayList<>(); for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) { int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1); List<Booking> daysBookings = new ArrayList<>(); for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) { String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>(); daysBookings.forEach((booking) -> { addBookingToSet(booking, bookedCourts); });// www. ja v a2s . c o m Booking booking; Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>(); do { // Loop until we create a booking of free courts int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1); int courtSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxCourtSpan + 1, numberOfCourts - court + 2)); int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1); int slotSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2)); booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2); booking.setDate(date.format(formatter)); courtsToBook.clear(); addBookingToSet(booking, courtsToBook); } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0)); daysBookings.add(booking); } bookings.addAll(daysBookings); } // Encode bookings as JSON // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // Create a json factory to write the treenode as json. JsonFactory jsonFactory = new JsonFactory(); ObjectNode rootNode = factory.objectNode(); ArrayNode bookingsNode = rootNode.putArray("bookings"); for (int i = 0; i < bookings.size(); i++) { Booking booking = bookings.get(i); ObjectNode bookingNode = factory.objectNode(); bookingNode.put("court", booking.getCourt()); bookingNode.put("courtSpan", booking.getCourtSpan()); bookingNode.put("slot", booking.getSlot()); bookingNode.put("slotSpan", booking.getSlotSpan()); bookingNode.put("name", booking.getName()); bookingNode.put("date", booking.getDate()); bookingsNode.add(bookingNode); } // Add empty booking rules array - just so restore works rootNode.putArray("bookingRules"); rootNode.put("clearBeforeRestore", true); try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"), JsonEncoding.UTF8)) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.setSerializationInclusion(Include.NON_NULL); mapper.writeTree(generator, rootNode); } }
From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());// w ww.ja v a 2 s . c om optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments formatter.setOptionComparator((o1, o2) -> { // I know this isn't fast, but who cares! The list is short. //noinspection SuspiciousMethodCalls return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2)); }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = ThreadLocalRandom.current(); Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line)); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:Main.java
public static void shuffleArray(PointF[] ar, int length) { // If running on Java 6 or older, use `new Random()` on RHS Random rnd;/*from ww w . j a v a 2 s . c om*/ if (Build.VERSION.SDK_INT >= 21) rnd = ThreadLocalRandom.current(); else rnd = new Random(); for (int i = length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap PointF a = ar[index]; ar[index] = ar[i]; ar[i] = a; } }