List of usage examples for java.util.concurrent.atomic AtomicBoolean set
public final void set(boolean newValue)
From source file:com.mapr.synth.Synth.java
public static void main(String[] args) throws IOException, CmdLineException, InterruptedException, ExecutionException { final Options opts = new Options(); CmdLineParser parser = new CmdLineParser(opts); try {//from w ww . ja v a2 s . c o m parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file " + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] " + "[-threads n] " + "[-output output-directory-name] "); throw e; } Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000, "Must have at least one thread and no more than 2000"); if (opts.threads > 1) { Preconditions.checkArgument(!"-".equals(opts.output), "If more than on thread is used, you have to use -output to set the output directory"); } File outputDir = new File(opts.output); if (!"-".equals(opts.output)) { if (!outputDir.exists()) { Preconditions.checkState(outputDir.mkdirs(), String.format("Couldn't create output directory %s", opts.output)); } Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(), String.format("Couldn't create directory %s", opts.output)); } if (opts.schema == null) { throw new IllegalArgumentException("Must specify schema file using [-schema filename] option"); } final SchemaSampler sampler = new SchemaSampler(opts.schema); final AtomicLong rowCount = new AtomicLong(); final List<ReportingWorker> tasks = Lists.newArrayList(); int limit = (opts.count + opts.threads - 1) / opts.threads; int remaining = opts.count; for (int i = 0; i < opts.threads; i++) { final int count = Math.min(limit, remaining); remaining -= count; tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i)); } final double t0 = System.nanoTime() * 1e-9; ExecutorService pool = Executors.newFixedThreadPool(opts.threads); ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1); final AtomicBoolean finalRun = new AtomicBoolean(false); final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log")); Runnable blink = new Runnable() { public double oldT; private long oldN; @Override public void run() { double t = System.nanoTime() * 1e-9; long n = rowCount.get(); System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads, t - t0, n, n / (t - t0), (n - oldN) / (t - oldT)); for (ReportingWorker task : tasks) { ReportingWorker.ThreadReport r = task.report(); sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime, r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime); } oldN = n; oldT = t; } }; if (!"-".equals(opts.output)) { blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS); } List<Future<Integer>> results = pool.invokeAll(tasks); int total = 0; for (Future<Integer> result : results) { total += result.get(); } Preconditions.checkState(total == opts.count, String .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total)); pool.shutdownNow(); blinker.shutdownNow(); finalRun.set(true); sideLog.close(); blink.run(); }
From source file:org.apache.pulsar.testclient.ManagedLedgerWriter.java
public static void main(String[] args) throws Exception { final Arguments arguments = new Arguments(); JCommander jc = new JCommander(arguments); jc.setProgramName("pulsar-perf-producer"); try {//ww w. j a v a2s . c om jc.parse(args); } catch (ParameterException e) { System.out.println(e.getMessage()); jc.usage(); System.exit(-1); } if (arguments.help) { jc.usage(); System.exit(-1); } arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime); // Dump config variables ObjectMapper m = new ObjectMapper(); ObjectWriter w = m.writerWithDefaultPrettyPrinter(); log.info("Starting Pulsar managed-ledger perf writer with config: {}", w.writeValueAsString(arguments)); byte[] payloadData = new byte[arguments.msgSize]; ByteBuf payloadBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(arguments.msgSize); payloadBuffer.writerIndex(arguments.msgSize); // Now processing command line arguments String managedLedgerPrefix = "test-" + DigestUtils.sha1Hex(UUID.randomUUID().toString()).substring(0, 5); ClientConfiguration bkConf = new ClientConfiguration(); bkConf.setUseV2WireProtocol(true); bkConf.setAddEntryTimeout(30); bkConf.setReadEntryTimeout(30); bkConf.setThrottleValue(0); bkConf.setNumChannelsPerBookie(arguments.maxConnections); bkConf.setZkServers(arguments.zookeeperServers); ManagedLedgerFactoryConfig mlFactoryConf = new ManagedLedgerFactoryConfig(); mlFactoryConf.setMaxCacheSize(0); ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkConf, mlFactoryConf); ManagedLedgerConfig mlConf = new ManagedLedgerConfig(); mlConf.setEnsembleSize(arguments.ensembleSize); mlConf.setWriteQuorumSize(arguments.writeQuorum); mlConf.setAckQuorumSize(arguments.ackQuorum); mlConf.setMinimumRolloverTime(10, TimeUnit.MINUTES); mlConf.setMetadataEnsembleSize(arguments.ensembleSize); mlConf.setMetadataWriteQuorumSize(arguments.writeQuorum); mlConf.setMetadataAckQuorumSize(arguments.ackQuorum); mlConf.setDigestType(arguments.digestType); mlConf.setMaxSizePerLedgerMb(2048); List<CompletableFuture<ManagedLedger>> futures = new ArrayList<>(); for (int i = 0; i < arguments.numManagedLedgers; i++) { String name = String.format("%s-%03d", managedLedgerPrefix, i); CompletableFuture<ManagedLedger> future = new CompletableFuture<>(); futures.add(future); factory.asyncOpen(name, mlConf, new OpenLedgerCallback() { @Override public void openLedgerComplete(ManagedLedger ledger, Object ctx) { future.complete(ledger); } @Override public void openLedgerFailed(ManagedLedgerException exception, Object ctx) { future.completeExceptionally(exception); } }, null); } List<ManagedLedger> managedLedgers = futures.stream().map(CompletableFuture::join) .collect(Collectors.toList()); log.info("Created {} managed ledgers", managedLedgers.size()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { printAggregatedStats(); } }); Collections.shuffle(managedLedgers); AtomicBoolean isDone = new AtomicBoolean(); List<List<ManagedLedger>> managedLedgersPerThread = Lists.partition(managedLedgers, Math.max(1, managedLedgers.size() / arguments.numThreads)); for (int i = 0; i < arguments.numThreads; i++) { List<ManagedLedger> managedLedgersForThisThread = managedLedgersPerThread.get(i); int nunManagedLedgersForThisThread = managedLedgersForThisThread.size(); long numMessagesForThisThread = arguments.numMessages / arguments.numThreads; int maxOutstandingForThisThread = arguments.maxOutstanding; executor.submit(() -> { try { final double msgRate = arguments.msgRate / (double) arguments.numThreads; final RateLimiter rateLimiter = RateLimiter.create(msgRate); // Acquire 1 sec worth of messages to have a slower ramp-up rateLimiter.acquire((int) msgRate); final long startTime = System.currentTimeMillis(); final Semaphore semaphore = new Semaphore(maxOutstandingForThisThread); final AddEntryCallback addEntryCallback = new AddEntryCallback() { @Override public void addComplete(Position position, Object ctx) { long sendTime = (Long) (ctx); messagesSent.increment(); bytesSent.add(payloadData.length); long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime); recorder.recordValue(latencyMicros); cumulativeRecorder.recordValue(latencyMicros); semaphore.release(); } @Override public void addFailed(ManagedLedgerException exception, Object ctx) { log.warn("Write error on message", exception); System.exit(-1); } }; // Send messages on all topics/producers long totalSent = 0; while (true) { for (int j = 0; j < nunManagedLedgersForThisThread; j++) { if (arguments.testTime > 0) { if (System.currentTimeMillis() - startTime > arguments.testTime) { log.info("------------------- DONE -----------------------"); printAggregatedStats(); isDone.set(true); Thread.sleep(5000); System.exit(0); } } if (numMessagesForThisThread > 0) { if (totalSent++ >= numMessagesForThisThread) { log.info("------------------- DONE -----------------------"); printAggregatedStats(); isDone.set(true); Thread.sleep(5000); System.exit(0); } } semaphore.acquire(); rateLimiter.acquire(); final long sendTime = System.nanoTime(); managedLedgersForThisThread.get(j).asyncAddEntry(payloadBuffer, addEntryCallback, sendTime); } } } catch (Throwable t) { log.error("Got error", t); } }); } // Print report stats long oldTime = System.nanoTime(); Histogram reportHistogram = null; while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { break; } if (isDone.get()) { break; } long now = System.nanoTime(); double elapsed = (now - oldTime) / 1e9; double rate = messagesSent.sumThenReset() / elapsed; double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8; reportHistogram = recorder.getIntervalHistogram(reportHistogram); log.info( "Throughput produced: {} msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0)); reportHistogram.reset(); oldTime = now; } factory.shutdown(); }
From source file:org.eclipse.swt.snippets.Snippet141.java
public static void main(String[] args) { display = new Display(); shell = new Shell(display); shell.setText("Snippet 141"); shell.setSize(300, 300);/*from w w w . j av a 2s .co m*/ shell.open(); shellGC = new GC(shell); shellBackground = shell.getBackground(); FileDialog dialog = new FileDialog(shell); dialog.setFilterExtensions(new String[] { "*.gif" }); String fileName = dialog.open(); final AtomicBoolean stopAnimation = new AtomicBoolean(false); if (fileName != null) { loader = new ImageLoader(); try { imageDataArray = loader.load(fileName); if (imageDataArray.length > 1) { animateThread = new Thread("Animation") { @Override public void run() { /* Create an off-screen image to draw on, and fill it with the shell background. */ Image offScreenImage = new Image(display, loader.logicalScreenWidth, loader.logicalScreenHeight); GC offScreenImageGC = new GC(offScreenImage); offScreenImageGC.setBackground(shellBackground); offScreenImageGC.fillRectangle(0, 0, loader.logicalScreenWidth, loader.logicalScreenHeight); try { /* Create the first image and draw it on the off-screen image. */ int imageDataIndex = 0; ImageData imageData = imageDataArray[imageDataIndex]; if (image != null && !image.isDisposed()) image.dispose(); image = new Image(display, imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); /* Now loop through the images, creating and drawing each one * on the off-screen image before drawing it on the shell. */ int repeatCount = loader.repeatCount; while ((loader.repeatCount == 0 || repeatCount > 0) && !stopAnimation.get()) { switch (imageData.disposalMethod) { case SWT.DM_FILL_BACKGROUND: /* Fill with the background color before drawing. */ Color bgColor = null; if (useGIFBackground && loader.backgroundPixel != -1) { bgColor = new Color(display, imageData.palette.getRGB(loader.backgroundPixel)); } offScreenImageGC.setBackground(bgColor != null ? bgColor : shellBackground); offScreenImageGC.fillRectangle(imageData.x, imageData.y, imageData.width, imageData.height); if (bgColor != null) bgColor.dispose(); break; case SWT.DM_FILL_PREVIOUS: /* Restore the previous image before drawing. */ offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); break; } imageDataIndex = (imageDataIndex + 1) % imageDataArray.length; imageData = imageDataArray[imageDataIndex]; image.dispose(); image = new Image(display, imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); /* Draw the off-screen image to the shell. */ shellGC.drawImage(offScreenImage, 0, 0); /* Sleep for the specified delay time (adding commonly-used slow-down fudge factors). */ try { int ms = imageData.delayTime * 10; if (ms < 20) ms += 30; if (ms < 30) ms += 10; Thread.sleep(ms); } catch (InterruptedException e) { } /* If we have just drawn the last image, decrement the repeat count and start again. */ if (imageDataIndex == imageDataArray.length - 1) repeatCount--; } } catch (SWTException ex) { System.out.println("There was an error animating the GIF"); } finally { if (offScreenImage != null && !offScreenImage.isDisposed()) offScreenImage.dispose(); if (offScreenImageGC != null && !offScreenImageGC.isDisposed()) offScreenImageGC.dispose(); if (image != null && !image.isDisposed()) image.dispose(); } } }; animateThread.setDaemon(true); animateThread.start(); } } catch (SWTException ex) { System.out.println("There was an error loading the GIF"); } } while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } stopAnimation.set(true); display.dispose(); }
From source file:Main.java
private static boolean deleteFileWithExceptsInner(File file, String suffix, String[] exceptFileNames, AtomicBoolean excepted) { String fileName = file.getName().toLowerCase(Locale.US); if (canDeleteWithSuffixInner(fileName, suffix) && !equalsFileNamesInner(fileName, exceptFileNames)) { return file.delete(); } else {//from ww w. ja va2 s . c om if (excepted != null) excepted.set(true); } return true; }
From source file:kn.uni.gis.foxhunt.context.GameContext.java
public static boolean isGameActive() { final AtomicBoolean bool = new AtomicBoolean(false); HttpContext.getInstance().get(currentGame.getGameUrl().toString(), new EntityHandlerAdapter() { @Override//ww w .j a v a2s. com public void handleEntity(HttpEntity entity, int statusCode) { bool.set(statusCode == HttpStatus.SC_OK); } }); return bool.get(); }
From source file:com.opinionlab.woa.WallOfAwesome.java
private static SockJSHandler makeEventStream(Vertx vertx) { final SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000); final SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options); sockJSHandler.socketHandler(socket -> { final AtomicInteger openCount = new AtomicInteger(); final AtomicBoolean running = new AtomicBoolean(true); LOGGER.info(format("[OPEN] Sockets: %d", openCount.incrementAndGet())); socket.endHandler(aVoid -> {/*www .ja v a 2 s . c om*/ running.set(false); LOGGER.info(format("[CLOSE] Sockets: %d", openCount.decrementAndGet())); }); socket.handler(buffer -> { String command = buffer.toString(); if ("purge".equals(command)) { EXECUTOR.execute(() -> { try { AwesomeImap.purge(s -> socket.write(buffer(objectToJson( HashTreePMap.empty().plus("deleted", true).plus("id", s.getId()), NO_TYPES)))); } catch (NoSuchProviderException e) { LOGGER.error("Could not purge messages", e); } }); } else { LOGGER.error(format("Unknown command: %s", command)); } }); try { final AtomicReference<Date> latestDate = new AtomicReference<>(new Date(0)); Consumer<Awesome> publishAwesome = awesome -> { socket.write(buffer(objectToJson(awesome, NO_TYPES))); final Date receivedDate = awesome.getReceivedDate(); if (latestDate.get().before(receivedDate)) { latestDate.set(receivedDate); } }; AwesomeImap.fetchAwesome().forEach(publishAwesome); EXECUTOR.execute(() -> { LOGGER.info("Polling started."); try { while (running.get()) { AwesomeImap.fetchAwesomeSince(latestDate.get()).forEach(publishAwesome); Thread.sleep(1000); } } catch (Throwable t) { running.set(false); socket.close(); LOGGER.error("Polling ended ABNORMALLY", t); } finally { LOGGER.info("Polling ended normally."); } }); } catch (MessagingException e) { LOGGER.error("Unable to fetch messages.", e); } }); return sockJSHandler; }
From source file:io.github.jeddict.jpa.modeler.properties.convert.ConvertPanel.java
static void importAttributeConverter(String classHandle, AtomicBoolean validated, ModelerFile modelerFile) { if (StringUtils.isBlank(classHandle)) { validated.set(true); return;// w w w.j ava 2s . co m } FileObject pkg = findSourceGroupForFile(modelerFile.getFileObject()).getRootFolder(); try { JavaSource javaSource = JavaSource.create(ClasspathInfo.create(pkg)); javaSource.runUserActionTask(controller -> { try { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement jc = controller.getElements().getTypeElement(classHandle); EntityMappings entityMappings = (EntityMappings) modelerFile.getDefinitionElement(); Optional<Converter> converter = entityMappings.findConverter(classHandle); if (jc != null) { DeclaredType attributeConverterType = null; if (!jc.getInterfaces().isEmpty()) { //fetch interface info for (TypeMirror interfaceType : jc.getInterfaces()) { if (interfaceType.getKind() == TypeKind.DECLARED && AttributeConverter.class .getName().equals(((DeclaredType) interfaceType).asElement().toString())) { attributeConverterType = (DeclaredType) interfaceType; } } } if (attributeConverterType != null && attributeConverterType.getTypeArguments().size() == 2) { TypeMirror attributeType = attributeConverterType.getTypeArguments().get(0); TypeMirror dbFieldType = attributeConverterType.getTypeArguments().get(1); if (!entityMappings.addConverter(classHandle, attributeType.toString(), dbFieldType.toString())) { message("MSG_ATTRIBUTE_CONVERTER_TYPE_CONFLICT", classHandle); } else { if (!converter.isPresent()) { message("MSG_ATTRIBUTE_CONVERTER_TYPE_REGISTERED", classHandle, attributeType.toString(), dbFieldType.toString()); } validated.set(true); } } else { message("MSG_ATTRIBUTE_CONVERTER_NOT_IMPLEMENTED", classHandle); } } else { if (converter.isPresent()) { validated.set(true); } else { message("MSG_ARTIFACT_NOT_FOUND", classHandle, pkg.getPath()); } } } catch (IOException t) { ExceptionUtils.printStackTrace(t); } }, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } }
From source file:com.google.gerrit.server.documentation.MarkdownFormatter.java
private static String readPegdownCss(AtomicBoolean file) throws IOException { String name = "pegdown.css"; URL url = MarkdownFormatter.class.getResource(name); if (url == null) { throw new FileNotFoundException("Resource " + name); }//from w w w . java2 s . co m file.set("file".equals(url.getProtocol())); try (InputStream in = url.openStream(); TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024)) { tmp.copy(in); return new String(tmp.toByteArray(), UTF_8); } }
From source file:com.offbynull.portmapper.common.ProcessUtils.java
/** * Run a process and dump the stdout stream to a string. * @param timeout maximum amount of time the process can take to run * @param command command//from w w w . java 2s . co m * @param args arguments * @return stdout from the process dumped to a string * @throws IOException if the process encounters an error * @throws NullPointerException if any arguments are {@code null} or contains {@code null} * @throws IllegalArgumentException any numeric argument is negative */ public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException { Validate.notNull(command); Validate.noNullElements(args); Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout); String[] pbCmd = new String[args.length + 1]; pbCmd[0] = command; System.arraycopy(args, 0, pbCmd, 1, args.length); ProcessBuilder builder = new ProcessBuilder(pbCmd); final AtomicBoolean failedFlag = new AtomicBoolean(); Timer timer = new Timer("Process timeout timer", true); Process proc = null; try { proc = builder.start(); final Process finalProc = proc; timer.schedule(new TimerTask() { @Override public void run() { failedFlag.set(true); finalProc.destroy(); } }, timeout); String ret = IOUtils.toString(proc.getInputStream()); if (failedFlag.get()) { throw new IOException("Process failed"); } return ret; } finally { if (proc != null) { proc.destroy(); } timer.cancel(); timer.purge(); } }
From source file:org.apache.hadoop.hbase.client.TestZKAsyncRegistry.java
static void waitUntilAllReplicasHavingRegionLocation(TableName tbl) throws IOException { TEST_UTIL.waitFor(TEST_UTIL.getConfiguration().getLong("hbase.client.sync.wait.timeout.msec", 60000), 200, true, new ExplainingPredicate<IOException>() { @Override//from w ww. java 2 s . co m public String explainFailure() throws IOException { return TEST_UTIL.explainTableAvailability(tbl); } @Override public boolean evaluate() throws IOException { AtomicBoolean ready = new AtomicBoolean(true); try { RegionLocations locs = REGISTRY.getMetaRegionLocation().get(); assertEquals(3, locs.getRegionLocations().length); IntStream.range(0, 3).forEach(i -> { HRegionLocation loc = locs.getRegionLocation(i); if (loc == null) { ready.set(false); } }); } catch (Exception e) { ready.set(false); } return ready.get(); } }); }