List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:io.cloudslang.worker.management.services.OutboundBufferTest.java
@Test public void longevityTest() throws InterruptedException { int THREADS_NUM = 5; long CHECK_DURATION = 5 * 1000L; long INFO_FREQUENCY = 2 * 1000L; final AtomicBoolean run = new AtomicBoolean(true); final CountDownLatch latch = new CountDownLatch(THREADS_NUM + 1); for (int i = 1; i <= THREADS_NUM; i++) { final int index = i; new Thread(new Runnable() { private final Class<? extends Message> messageClass = (index % 2) != 0 ? DummyMsg1.class : DummyMsg2.class; @Override//from w w w . j ava 2s .c om public void run() { int counter = 0; try { logger.debug("started, will generate messages of " + messageClass.getSimpleName()); while (run.get()) { buffer.put(messageClass.newInstance()); counter++; Thread.sleep(5L); } logger.debug("thread finished. processed " + counter + " messages"); } catch (Exception ex) { logger.error("thread finished", ex); } finally { latch.countDown(); } } }, "T-" + i).start(); } final DrainStatistics statistics = new DrainStatistics(); //noinspection unchecked doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { @SuppressWarnings("unchecked") List<Message> messages = (List<Message>) invocation.getArguments()[0]; int weight = 0; for (Message message : messages) weight += message.getWeight(); statistics.add(messages.size(), weight); return null; } }).when(dispatcherService).dispatch(anyList(), anyString(), anyString(), anyString()); new Thread(new Runnable() { @Override public void run() { try { logger.debug("started"); while (run.get()) { buffer.drain(); Thread.sleep(30L); } while (buffer.getSize() > 0) buffer.drain(); } catch (Exception ex) { logger.error("thread finished", ex); } finally { latch.countDown(); } } }, "T-D").start(); long t = System.currentTimeMillis(); while (System.currentTimeMillis() - t < CHECK_DURATION) { Thread.sleep(INFO_FREQUENCY); logger.debug(buffer.getStatus()); } run.set(false); latch.await(); System.out.println("Drain statistics: " + statistics.report()); }
From source file:biz.ganttproject.impex.csv.CsvImportTest.java
public void testSkipLinesWithEmptyMandatoryFields() throws IOException { String header = "A, B, C"; String data1 = "a1,,c1"; String data2 = "a2,b2,c2"; String data3 = ",b3,c3"; final AtomicBoolean wasCalled = new AtomicBoolean(false); RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B", "C"), ImmutableSet.<String>of("A", "B")) { @Override// ww w . j a v a 2 s .c o m protected boolean doProcess(CSVRecord record) { if (!super.doProcess(record)) { return false; } if (!hasMandatoryFields(record)) { return false; } wasCalled.set(true); assertEquals("a2", record.get("A")); assertEquals("b2", record.get("B")); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data1, data2, data3)), recordGroup); importer.load(); assertTrue(wasCalled.get()); assertEquals(2, importer.getSkippedLineCount()); }
From source file:org.alfresco.repo.activities.feed.FeedNotifierImpl.java
public void execute(int repeatIntervalMins) { checkProperties();/* ww w.j a v a 2 s. co m*/ // Bypass if the system is in read-only mode if (transactionService.isReadOnly()) { if (logger.isDebugEnabled()) { logger.debug("Activities email notification bypassed; the system is read-only"); } return; } String lockToken = null; // Use a flag to keep track of the running job final AtomicBoolean running = new AtomicBoolean(true); try { lockToken = jobLockService.getLock(LOCK_QNAME, LOCK_TTL); if (lockToken == null) { logger.info("Can't get lock. Assume multiple feed notifiers..."); return; } if (logger.isTraceEnabled()) { logger.trace("Activities email notification started"); } jobLockService.refreshLock(lockToken, LOCK_QNAME, LOCK_TTL, new JobLockRefreshCallback() { @Override public boolean isActive() { return running.get(); } @Override public void lockReleased() { running.set(false); } }); executeInternal(repeatIntervalMins); // Done if (logger.isTraceEnabled()) { logger.trace("Activities email notification completed"); } } catch (LockAcquisitionException e) { // Job being done by another process if (logger.isDebugEnabled()) { logger.debug("Activities email notification already underway"); } } catch (VmShutdownException e) { // Aborted if (logger.isDebugEnabled()) { logger.debug("Activities email notification aborted"); } } finally { // The lock will self-release if answer isActive in the negative running.set(false); if (lockToken != null) { jobLockService.releaseLock(lockToken, LOCK_QNAME); } } }
From source file:it.anyplace.sync.client.SyncthingClient.java
private BlockExchangeConnectionHandler openConnection(DeviceAddress deviceAddress) throws Exception { final BlockExchangeConnectionHandler connectionHandler = new BlockExchangeConnectionHandler(configuration, deviceAddress);//from w ww .j av a 2 s. co m connectionHandler.setIndexHandler(indexHandler); connectionHandler.getEventBus().register(indexHandler); connectionHandler.getEventBus().register(devicesHandler); final AtomicBoolean shouldRestartForNewFolder = new AtomicBoolean(false); connectionHandler.getEventBus().register(new Object() { @Subscribe public void handleConnectionClosedEvent(BlockExchangeConnectionHandler.ConnectionClosedEvent event) { connections.remove(connectionHandler); synchronized (pool) { pool.remove(connectionHandler); } } @Subscribe public void handleNewFolderSharedEvent(BlockExchangeConnectionHandler.NewFolderSharedEvent event) { shouldRestartForNewFolder.set(true); } }); connectionHandler.connect(); connections.add(connectionHandler); if (shouldRestartForNewFolder.get()) { logger.info("restart connection for new folder shared"); connectionHandler.close(); return openConnection(deviceAddress); } else { return connectionHandler; } }
From source file:ch.cyberduck.core.b2.B2LargeUploadServiceTest.java
@Test public void testAppendSecondPart() throws Exception { final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(), new Credentials(System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")))); session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final int length = 102 * 1024 * 1024; final byte[] content = RandomUtils.nextBytes(length); IOUtils.write(content, local.getOutputStream(false)); final TransferStatus status = new TransferStatus(); status.setLength(content.length);//from w w w. j a va 2s . c om final AtomicBoolean interrupt = new AtomicBoolean(); try { new B2LargeUploadService(session, new B2WriteFeature(session), 100L * 1024L * 1024L, 1).upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener() { long count; @Override public void sent(final long bytes) { count += bytes; if (count >= 101L * 1024L * 1024L) { throw new RuntimeException(); } } }, status, new DisabledLoginCallback()); } catch (BackgroundException e) { // Expected interrupt.set(true); } assertTrue(interrupt.get()); assertEquals(100L * 1024L * 1024L, status.getOffset(), 0L); assertFalse(status.isComplete()); final TransferStatus append = new TransferStatus().append(true).length(2L * 1024L * 1024L) .skip(100L * 1024L * 1024L); new B2LargeUploadService(session, new B2WriteFeature(session), 100L * 1024L * 1024L, 1).upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), append, new DisabledLoginCallback()); assertEquals(102L * 1024L * 1024L, append.getOffset(), 0L); assertTrue(append.isComplete()); assertTrue(new B2FindFeature(session).find(test)); assertEquals(102L * 1024L * 1024L, new B2AttributesFinderFeature(session).find(test).getSize(), 0L); final byte[] buffer = new byte[content.length]; final InputStream in = new B2ReadFeature(session).read(test, new TransferStatus(), new DisabledConnectionCallback()); IOUtils.readFully(in, buffer); in.close(); assertArrayEquals(content, buffer); new B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); local.delete(); session.close(); }
From source file:com.yahoo.sql4d.sql4ddriver.sql.MysqlAccessor.java
/** * Suitable for CRUD operations where no result set is expected. * @param params//from w w w .j a va 2 s.c o m * @param query * @return */ public boolean execute(Map<String, String> params, String query) { final AtomicBoolean result = new AtomicBoolean(false); Tuple2<DataSource, Connection> conn = null; try { conn = getConnection(); NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1()); jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() { @Override public Void doInPreparedStatement(PreparedStatement ps) { try { result.set(ps.execute()); } catch (SQLException e) { result.set(false); } return null; } }); } catch (Exception ex) { Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex); result.set(false); } finally { returnConnection(conn); } return result.get(); }
From source file:org.apache.hadoop.hbase.regionserver.handler.OpenRegionHandler.java
/** * Update ZK or META. This can take a while if for example the * hbase:meta is not available -- if server hosting hbase:meta crashed and we are * waiting on it to come back -- so run in a thread and keep updating znode * state meantime so master doesn't timeout our region-in-transition. * Caller must cleanup region if this fails. */// w w w .j a v a2s . co m boolean updateMeta(final HRegion r) { if (this.server.isStopped() || this.rsServices.isStopping()) { return false; } // Object we do wait/notify on. Make it boolean. If set, we're done. // Else, wait. final AtomicBoolean signaller = new AtomicBoolean(false); PostOpenDeployTasksThread t = new PostOpenDeployTasksThread(r, this.server, this.rsServices, signaller); t.start(); // Post open deploy task: // meta => update meta location in ZK // other region => update meta // It could fail if ZK/meta is not available and // the update runs out of retries. long now = System.currentTimeMillis(); long lastUpdate = now; boolean tickleOpening = true; while (!signaller.get() && t.isAlive() && !this.server.isStopped() && !this.rsServices.isStopping() && isRegionStillOpening()) { long elapsed = now - lastUpdate; if (elapsed > 120000) { // 2 minutes, no need to tickleOpening too often // Only tickle OPENING if postOpenDeployTasks is taking some time. lastUpdate = now; tickleOpening = tickleOpening("post_open_deploy"); } synchronized (signaller) { try { // Wait for 10 seconds, so that server shutdown // won't take too long if this thread happens to run. signaller.wait(10000); } catch (InterruptedException e) { // Go to the loop check. } } now = System.currentTimeMillis(); } // Is thread still alive? We may have left above loop because server is // stopping or we timed out the edit. Is so, interrupt it. if (t.isAlive()) { if (!signaller.get()) { // Thread still running; interrupt LOG.debug("Interrupting thread " + t); t.interrupt(); } try { t.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted joining " + r.getRegionInfo().getRegionNameAsString(), ie); Thread.currentThread().interrupt(); } } // Was there an exception opening the region? This should trigger on // InterruptedException too. If so, we failed. Even if tickle opening fails // then it is a failure. return ((!Thread.interrupted() && t.getException() == null) && tickleOpening); }
From source file:org.apache.hadoop.hbase.regionserver.TestRegionReplicas.java
@Test(timeout = 300000) public void testFlushAndCompactionsInPrimary() throws Exception { long runtime = 30 * 1000; // enable store file refreshing final int refreshPeriod = 100; // 100ms refresh is a lot HTU.getConfiguration().setInt("hbase.hstore.compactionThreshold", 3); HTU.getConfiguration().setInt(StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, refreshPeriod); // restart the region server so that it starts the refresher chore restartRegionServer();/*www . ja v a 2 s .com*/ final int startKey = 0, endKey = 1000; try { openRegion(HTU, getRS(), hriSecondary); //load some data to primary so that reader won't fail HTU.loadNumericRows(table, f, startKey, endKey); TestRegionServerNoMaster.flushRegion(HTU, hriPrimary); // ensure that chore is run Threads.sleep(2 * refreshPeriod); final AtomicBoolean running = new AtomicBoolean(true); @SuppressWarnings("unchecked") final AtomicReference<Exception>[] exceptions = new AtomicReference[3]; for (int i = 0; i < exceptions.length; i++) { exceptions[i] = new AtomicReference<Exception>(); } Runnable writer = new Runnable() { int key = startKey; @Override public void run() { try { while (running.get()) { byte[] data = Bytes.toBytes(String.valueOf(key)); Put put = new Put(data); put.add(f, null, data); table.put(put); key++; if (key == endKey) key = startKey; } } catch (Exception ex) { LOG.warn(ex); exceptions[0].compareAndSet(null, ex); } } }; Runnable flusherCompactor = new Runnable() { Random random = new Random(); @Override public void run() { try { while (running.get()) { // flush or compact if (random.nextBoolean()) { TestRegionServerNoMaster.flushRegion(HTU, hriPrimary); } else { HTU.compact(table.getName(), random.nextBoolean()); } } } catch (Exception ex) { LOG.warn(ex); exceptions[1].compareAndSet(null, ex); } } }; Runnable reader = new Runnable() { Random random = new Random(); @Override public void run() { try { while (running.get()) { // whether to do a close and open if (random.nextInt(10) == 0) { try { closeRegion(HTU, getRS(), hriSecondary); } catch (Exception ex) { LOG.warn("Failed closing the region " + hriSecondary + " " + StringUtils.stringifyException(ex)); exceptions[2].compareAndSet(null, ex); } try { openRegion(HTU, getRS(), hriSecondary); } catch (Exception ex) { LOG.warn("Failed opening the region " + hriSecondary + " " + StringUtils.stringifyException(ex)); exceptions[2].compareAndSet(null, ex); } } int key = random.nextInt(endKey - startKey) + startKey; assertGetRpc(hriSecondary, key, true); } } catch (Exception ex) { LOG.warn("Failed getting the value in the region " + hriSecondary + " " + StringUtils.stringifyException(ex)); exceptions[2].compareAndSet(null, ex); } } }; LOG.info("Starting writer and reader"); ExecutorService executor = Executors.newFixedThreadPool(3); executor.submit(writer); executor.submit(flusherCompactor); executor.submit(reader); // wait for threads Threads.sleep(runtime); running.set(false); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); for (AtomicReference<Exception> exRef : exceptions) { Assert.assertNull(exRef.get()); } } finally { HTU.deleteNumericRows(table, HConstants.CATALOG_FAMILY, startKey, endKey); closeRegion(HTU, getRS(), hriSecondary); } }
From source file:com.google.dart.java2dart.SyntaxTranslator.java
private static boolean hasConstructorInvocation(org.eclipse.jdt.core.dom.ASTNode node) { final AtomicBoolean result = new AtomicBoolean(); node.accept(new ASTVisitor() { @Override/*from w ww. jav a 2 s . c om*/ public boolean visit(ConstructorInvocation node) { result.set(true); return false; } }); return result.get(); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldRaiseExceptionInWithResultOfLifeCycle() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final GremlinExecutor.LifeCycle lc = GremlinExecutor.LifeCycle.build().withResult(r -> { throw new RuntimeException("no worky"); }).create();/*from w ww. j av a2s . c o m*/ final AtomicBoolean exceptionRaised = new AtomicBoolean(false); final CompletableFuture<Object> future = gremlinExecutor.eval("1+1", "gremlin-groovy", new SimpleBindings(), lc); future.handle((r, t) -> { exceptionRaised.set(t != null && t instanceof RuntimeException && t.getMessage().equals("no worky")); return null; }).get(); assertThat(exceptionRaised.get(), is(true)); gremlinExecutor.close(); }