List of usage examples for java.util.concurrent.atomic AtomicBoolean set
public final void set(boolean newValue)
From source file:com.github.lynxdb.server.core.repository.TimeSerieRepo.java
public ChainableIterator<TimeSerie> find(UUID _vhost, String _name, Map<String, String> _tags, long _start, long _end) { return findRows(_vhost, _name, _tags, _start, _end).map( (ChainableIterator.Func1<ChainableIterator<TS>, TimeSerie>) (ChainableIterator<TS> _source) -> { Map<String, String> tags = new HashMap<>(); AtomicBoolean tagsLoaded = new AtomicBoolean(false); return new TimeSerie(_name, tags, new ChainableIterator<Entry>() { Iterator<Row> current = null; @Override//w w w . j a v a2s . com public boolean hasNext() { if (current != null && current.hasNext()) { return true; } while (_source.hasNext()) { TS newTS = _source.next(); if (!tagsLoaded.get()) { tagsLoaded.set(true); tags.putAll(newTS.tags); } long start = System.currentTimeMillis(); current = ct.query(QueryBuilder.select("time", "value").from("series") .where(QueryBuilder.eq("vhostid", _vhost)) .and(QueryBuilder.eq("name", _name)) .and(QueryBuilder.eq("tags", newTS.serialized)) .and(QueryBuilder.eq("group", newTS.group)) .and(QueryBuilder.gte("time", _start)).and(QueryBuilder.lte("time", _end)) .orderBy(QueryBuilder.desc("time"))).iterator(); csMonit.tsFetchQueryTime.add((int) (System.currentTimeMillis() - start)); csMonit.queryFetchCount.incrementAndGet(); if (current.hasNext()) { return true; } } return false; } @Override public Entry next() { Row r = current.next(); return new Entry(r.getInt("time"), r.getDouble("value")); } }); }); }
From source file:org.apache.bookkeeper.bookie.Bookie.java
public static void checkDirectoryStructure(File dir) throws IOException { if (!dir.exists()) { File parent = dir.getParentFile(); File preV3versionFile = new File(dir.getParent(), BookKeeperConstants.VERSION_FILENAME); final AtomicBoolean oldDataExists = new AtomicBoolean(false); parent.list(new FilenameFilter() { @Override/*from w ww . j a v a 2s.c o m*/ public boolean accept(File dir, String name) { if (name.endsWith(".txn") || name.endsWith(".idx") || name.endsWith(".log")) { oldDataExists.set(true); } return true; } }); if (preV3versionFile.exists() || oldDataExists.get()) { String err = "Directory layout version is less than 3, upgrade needed"; LOG.error(err); throw new IOException(err); } if (!dir.mkdirs()) { String err = "Unable to create directory " + dir; LOG.error(err); throw new IOException(err); } } }
From source file:com.tc.process.Exec.java
@SuppressWarnings("resource") public static Result execute(final Process process, String cmd[], String outputLog, byte[] input, File workingDir, final long timeout) throws Exception { final AtomicBoolean processFinished = new AtomicBoolean(); if (timeout > 0) { Thread timeoutThread = new Thread() { @Override/*from w w w .j a v a2 s .com*/ public void run() { ThreadUtil.reallySleep(timeout); if (!processFinished.get()) { process.destroy(); } } }; timeoutThread.start(); } Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog != null) { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } else { stderr = new StreamCollector(process.getErrorStream()); stdout = new StreamCollector(process.getInputStream()); stderr.start(); stdout.start(); } inputThread.start(); final int exitCode = process.waitFor(); processFinished.set(true); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } return new Result(cmd, outString, errString, exitCode); } finally { closeQuietly(fileOutput); } }
From source file:org.zodiark.service.publisher.PublisherServiceImpl.java
private boolean validateSubscriberState(String subscriberId, final PublisherEndpoint p) { final AtomicBoolean isValid = new AtomicBoolean(); // DAangerous if the path change. eventBus.message(RETRIEVE_SUBSCRIBER, subscriberId, new Reply<SubscriberEndpoint, String>() { @Override//from ww w . ja va 2s. c om public void ok(SubscriberEndpoint s) { isValid.set(s.publisherEndpoint().equals(p)); } @Override public void fail(ReplyException replyException) { logger.error("No Endpoint"); } }); return isValid.get(); }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManagerTest.java
@Test public void testChooseClientAliasStartcom() throws Exception { final AtomicBoolean choose = new AtomicBoolean(); final X509KeyManager m = new CertificateStoreX509KeyManager(new DisabledCertificateStore() { @Override//w w w.jav a2s.c o m public X509Certificate choose(String[] keyTypes, Principal[] issuers, String hostname, String prompt) throws ConnectionCanceledException { assertEquals( "The server requires a certificate to validate your identity. Select the certificate to authenticate yourself to test.cyberduck.ch.", prompt); for (Principal issuer : issuers) { assertEquals("CN=StartCom Class 2 Primary Intermediate Client CA", issuer.getName()); } choose.set(true); throw new ConnectionCanceledException(); } }).init(); assertNull(m.chooseClientAlias(new String[] { "RSA", "DSA" }, new Principal[] { new X500Principal("CN=StartCom Class 2 Primary Intermediate Client CA") }, new Socket("test.cyberduck.ch", 443))); assertTrue(choose.get()); }
From source file:org.apache.cayenne.access.dbsync.BaseSchemaUpdateStrategy_ConcurrencyTest.java
@Test public void testUpdateSchema_Concurrency() throws InterruptedException, ExecutionException, TimeoutException { final AtomicInteger counter = new AtomicInteger(); final AtomicBoolean errors = new AtomicBoolean(false); final BaseSchemaUpdateStrategy strategy = new BaseSchemaUpdateStrategy() { @Override// w w w.ja v a2 s .com protected void processSchemaUpdate(DataNode dataNode) throws SQLException { counter.incrementAndGet(); } }; Collection<Future<?>> tasks = new ArrayList<>(); for (int i = 0; i < 20; i++) { tasks.add(threadPool.submit(new Runnable() { @Override public void run() { try { strategy.updateSchema(dataNode); } catch (Throwable e) { LOGGER.error("error in test", e); errors.set(true); } } })); } for (Future<?> f : tasks) { f.get(1, TimeUnit.SECONDS); } assertFalse(errors.get()); assertEquals(1, counter.get()); }
From source file:io.nats.client.ITClusterTest.java
@Test public void testProperFalloutAfterMaxAttempts() throws Exception { Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5) .reconnectWait(25, TimeUnit.MILLISECONDS).build(); opts.servers = Nats.processUrlArray(testServers); final CountDownLatch dcLatch = new CountDownLatch(1); opts.disconnectedCb = new DisconnectedCallback() { public void onDisconnect(ConnectionEvent event) { dcLatch.countDown();/*from w w w.ja va 2 s. c om*/ } }; final AtomicBoolean closedCbCalled = new AtomicBoolean(false); final CountDownLatch ccLatch = new CountDownLatch(1); opts.closedCb = new ClosedCallback() { public void onClose(ConnectionEvent event) { closedCbCalled.set(true); ccLatch.countDown(); } }; try (NatsServer s1 = runServerOnPort(1222)) { try (Connection c = opts.connect()) { s1.shutdown(); // wait for disconnect assertTrue("Did not receive a disconnect callback message", await(dcLatch, 2, TimeUnit.SECONDS)); // Wait for ClosedCB assertTrue("Did not receive a closed callback message", await(ccLatch, 2, TimeUnit.SECONDS)); // Make sure we are not still reconnecting. assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get()); // Expect connection to be closed... assertTrue("Wrong status: " + c.getState(), c.isClosed()); } } }
From source file:de.speexx.jira.jan.command.transition.IssueTransitionFetcher.java
void exportAsCsv(final List<IssueInfo> issues, final AtomicBoolean doHeader) { try {/*from w ww . j av a2 s . co m*/ final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), RFC4180); final String[] header = new String[] { "issue-key", "type", "issue-creation-datetime", "priority", "resolution", "from-stage", "stage", "stage-enter-datetime", "stage-duration" }; if (!doHeader.get()) { csvPrinter.printRecord((Object[]) header); doHeader.set(true); } issues.forEach(info -> { info.stageInfoAsDuration().forEach(stageDuration -> { final String[] values = new String[header.length]; values[0] = info.key; values[1] = info.issueType; values[2] = DateTimeFormatter.ISO_DATE_TIME.format(info.created); values[3] = info.priority; values[4] = resolutionAdjustment(info); values[5] = stageDuration.fromStageName != null ? "" + stageDuration.fromStageName : ""; values[6] = "" + stageDuration.stageName; values[7] = DateTimeFormatter.ISO_DATE_TIME.format(stageDuration.stageStart); values[8] = "" + stageDuration.getDurationSeconds(); try { csvPrinter.printRecord((Object[]) values); } catch (final IOException e) { throw new JiraAnalyzeException(e); } }); }); csvPrinter.flush(); } catch (final IOException e) { throw new JiraAnalyzeException(e); } }
From source file:com.datatorrent.stram.engine.GenericNodeTest.java
@SuppressWarnings("SleepWhileInLoop") private void testDoubleCheckpointHandling(ProcessingMode processingMode) throws Exception { WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"), 1024);//from w w w . jav a 2s . co m windowGenerator.setResetWindow(0L); windowGenerator.setFirstWindow(0L); windowGenerator.setWindowWidth(100); windowGenerator.setCheckpointCount(1, 0); GenericCheckpointOperator gco = new GenericCheckpointOperator(); DefaultAttributeMap dam = new DefaultAttributeMap(); dam.put(OperatorContext.APPLICATION_WINDOW_COUNT, 2); dam.put(OperatorContext.CHECKPOINT_WINDOW_COUNT, 2); dam.put(OperatorContext.PROCESSING_MODE, processingMode); final GenericNode in = new GenericNode(gco, new com.datatorrent.stram.engine.OperatorContext(0, dam, null)); in.setId(1); TestSink testSink = new TestSink(); in.connectInputPort("ip1", windowGenerator.acquireReservoir(String.valueOf(in.id), 1024)); in.connectOutputPort("output", testSink); in.firstWindowMillis = 0; in.windowWidthMillis = 100; windowGenerator.activate(null); final AtomicBoolean ab = new AtomicBoolean(false); Thread t = new Thread() { @Override public void run() { ab.set(true); in.activate(); in.run(); in.deactivate(); } }; t.start(); long startTime = System.currentTimeMillis(); long endTime = 0; while (gco.numWindows < 3 && ((endTime = System.currentTimeMillis()) - startTime) < 5000) { Thread.sleep(50); } in.shutdown(); t.join(); windowGenerator.deactivate(); Assert.assertFalse(gco.checkpointTwice); Assert.assertTrue("Timed out", (endTime - startTime) < 5000); }
From source file:org.apache.blur.shell.QueryCommand.java
private void doItInternal(Blur.Iface client, String[] args, PrintWriter out) throws FinishedException, BlurException, TException { CommandLine commandLine = QueryCommandHelper.parse(args, out, name() + " " + usage()); if (commandLine == null) { return;/*from w w w. j a v a 2 s . c o m*/ } BlurQuery blurQuery = QueryCommandHelper.getBlurQuery(commandLine); if (Main.debug) { out.println(blurQuery); } _width = 100; if (commandLine.hasOption(QueryCommandHelper.WIDTH)) { _width = Integer.parseInt(commandLine.getOptionValue(QueryCommandHelper.WIDTH)); } String tablename = args[1]; long s = System.nanoTime(); BlurResults blurResults = client.query(tablename, blurQuery); long e = System.nanoTime(); long timeInNanos = e - s; if (blurResults.getTotalResults() == 0) { out.println("No results found in [" + timeInNanos / 1000000.0 + " ms]."); return; } ConsoleReader reader = getConsoleReader(); if (reader == null) { String description = blurResults.getTotalResults() + " results found in [" + timeInNanos / 1000000.0 + " ms]. " + getFetchMetaData(blurResults); out.println(description); List<BlurResult> results = blurResults.getResults(); for (BlurResult result : results) { print(out, result); } return; } String prompt = reader.getPrompt(); reader.setPrompt(""); final TableDisplay tableDisplay = new TableDisplay(reader); tableDisplay.setDescription(white(blurResults.getTotalResults() + " results found in [" + timeInNanos / 1000000.0 + " ms]. " + getFetchMetaData(blurResults))); tableDisplay.setSeperator(" "); try { final AtomicBoolean viewing = new AtomicBoolean(true); tableDisplay.addKeyHook(new Runnable() { @Override public void run() { synchronized (viewing) { viewing.set(false); viewing.notify(); tableDisplay.setStopReadingInput(true); } } }, 'q'); RenderType type = getRenderRype(blurResults); switch (type) { case ROW_MULTI_FAMILY: renderRowMultiFamily(tableDisplay, blurResults); break; case ROW_SINGLE_FAMILY: renderRowSingleFamily(tableDisplay, blurResults); break; default: break; } while (viewing.get()) { synchronized (viewing) { try { viewing.wait(); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } } } finally { try { tableDisplay.close(); } catch (IOException ex) { if (Main.debug) { ex.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException ex) { if (Main.debug) { ex.printStackTrace(); } } try { reader.setPrompt(""); reader.clearScreen(); } catch (IOException ex) { if (Main.debug) { ex.printStackTrace(); } } out.write("\u001B[0m"); out.flush(); reader.setPrompt(prompt); } }