Example usage for java.util.concurrent.atomic AtomicBoolean set

List of usage examples for java.util.concurrent.atomic AtomicBoolean set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean set.

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.barchart.http.server.TestHttpServer.java

@Test
public void testShutdown() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final AtomicBoolean pass = new AtomicBoolean(false);

    executor.schedule(new Runnable() {

        @Override/*ww w .  ja  v a 2  s . co  m*/
        public void run() {

            try {
                server.shutdown().sync();
            } catch (final InterruptedException e1) {
                e1.printStackTrace();
            }

            try {
                client.execute(new HttpGet("http://localhost:" + port + "/basic"));
            } catch (final HttpHostConnectException hhce) {
                pass.set(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

    }, 1000, TimeUnit.MILLISECONDS);

    final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect");
    final HttpResponse response = client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    // assertTrue(pass.get());

}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanTasksForSwarm(String swarmClusterId) {

    logger.info("scanning tasks for swarm: {}", swarmClusterId);

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    JsonNode response = getRestClient().getTasks();
    response.forEach(it -> {//from  w  ww.j av a  2s  .  c  om
        try {
            earlistUpdate.set(Math.min(earlistUpdate.get(), saveTask(it)));

        } catch (Exception e) {
            logger.warn("problem updating task", e);
            error.set(true);
        }
    });

    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerTask) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperFalloutAfterMaxAttemptsWithAuthMismatch() throws Exception {
    final String[] myServers = { "nats://localhost:1222", "nats://localhost:4443" };

    Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5)
            .reconnectWait(25, TimeUnit.MILLISECONDS).build();
    opts.servers = Nats.processUrlArray(myServers);

    final CountDownLatch dcLatch = new CountDownLatch(1);
    opts.disconnectedCb = new DisconnectedCallback() {
        public void onDisconnect(ConnectionEvent event) {
            dcLatch.countDown();//from   w  ww .j a va  2s .  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 (NatsServer s2 = runServerWithConfig("tlsverify.conf")) {
            try (ConnectionImpl nc = (ConnectionImpl) opts.connect()) {
                s1.shutdown();

                // wait for disconnect
                assertTrue("Did not receive a disconnect callback message",
                        await(dcLatch, 5, TimeUnit.SECONDS));

                // Wait for ClosedCB
                assertTrue("Did not receive a closed callback message", await(ccLatch, 5, TimeUnit.SECONDS));

                // Make sure we are not still reconnecting.
                assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

                // Make sure we have not exceeded MaxReconnect
                assertEquals("Wrong number of reconnects", nc.getOptions().getMaxReconnect(),
                        nc.getStats().getReconnects());

                // 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: " + nc.getState(), nc.isClosed());
            }
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldCallSuccess() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeoutCalled.set(true)).create();
    assertEquals(2, gremlinExecutor.eval("1+1").get());

    // need to wait long enough for the callback to register
    Thread.sleep(500);/*from   ww  w.j a v  a 2s.  c  om*/

    assertFalse(timeoutCalled.get());
    assertTrue(successCalled.get());
    assertFalse(failureCalled.get());
    gremlinExecutor.close();
}

From source file:org.alfresco.repo.activities.feed.cleanup.FeedCleaner.java

public int execute() throws JobExecutionException {
    checkProperties();/*w ww . ja  va2 s . com*/

    final AtomicBoolean keepGoing = new AtomicBoolean(true);
    String lockToken = null;
    try {
        // Lock
        lockToken = jobLockService.getLock(LOCK_QNAME, LOCK_TTL);
        // Refresh to get callbacks
        JobLockRefreshCallback callback = new JobLockRefreshCallback() {
            @Override
            public void lockReleased() {
                keepGoing.set(false);
            }

            @Override
            public boolean isActive() {
                return keepGoing.get();
            }
        };
        jobLockService.refreshLock(lockToken, LOCK_QNAME, LOCK_TTL, callback);
        int cleaned = executeWithLock(keepGoing);
        if (logger.isDebugEnabled()) {
            logger.debug("Cleaned " + cleaned + " feed entries.");
        }
    } catch (LockAcquisitionException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping feed cleaning.  " + e.getMessage());
        }
    } finally {
        keepGoing.set(false); // Notify the refresh callback that we are done
        if (lockToken != null) {
            jobLockService.releaseLock(lockToken, LOCK_QNAME);
        }
    }
    return 0;
}

From source file:org.apache.hadoop.yarn.applications.ivic.TestDistributedShell.java

public void testDSShell(boolean haveDomain) throws Exception {
    String[] args = { "--jar", APPMASTER_JAR, "--num_containers", "2", "--shell_command",
            Shell.WINDOWS ? "dir" : "ls", "--master_memory", "512", "--master_vcores", "2",
            "--container_memory", "128", "--container_vcores", "1" };
    if (haveDomain) {
        String[] domainArgs = { "--domain", "TEST_DOMAIN", "--view_acls", "reader_user reader_group",
                "--modify_acls", "writer_user writer_group", "--create" };
        List<String> argsList = new ArrayList<String>(Arrays.asList(args));
        argsList.addAll(Arrays.asList(domainArgs));
        args = argsList.toArray(new String[argsList.size()]);
    }/*from ww  w.ja v a 2s.c  o m*/

    LOG.info("Initializing DS Client");
    final Client client = new Client(new Configuration(yarnCluster.getConfig()));
    boolean initSuccess = client.init(args);
    Assert.assertTrue(initSuccess);
    LOG.info("Running DS Client");
    final AtomicBoolean result = new AtomicBoolean(false);
    Thread t = new Thread() {
        public void run() {
            try {
                result.set(client.run());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    t.start();

    YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(new Configuration(yarnCluster.getConfig()));
    yarnClient.start();
    String hostName = NetUtils.getHostname();

    boolean verified = false;
    String errorMessage = "";
    while (!verified) {
        List<ApplicationReport> apps = yarnClient.getApplications();
        if (apps.size() == 0) {
            Thread.sleep(10);
            continue;
        }
        ApplicationReport appReport = apps.get(0);
        if (appReport.getHost().equals("N/A")) {
            Thread.sleep(10);
            continue;
        }
        errorMessage = "Expected host name to start with '" + hostName + "', was '" + appReport.getHost()
                + "'. Expected rpc port to be '-1', was '" + appReport.getRpcPort() + "'.";
        if (checkHostname(appReport.getHost()) && appReport.getRpcPort() == -1) {
            verified = true;
        }
        if (appReport.getYarnApplicationState() == YarnApplicationState.FINISHED) {
            break;
        }
    }
    Assert.assertTrue(errorMessage, verified);
    t.join();
    LOG.info("Client run completed. Result=" + result);
    Assert.assertTrue(result.get());

    TimelineDomain domain = null;
    if (haveDomain) {
        domain = yarnCluster.getApplicationHistoryServer().getTimelineStore().getDomain("TEST_DOMAIN");
        Assert.assertNotNull(domain);
        Assert.assertEquals("reader_user reader_group", domain.getReaders());
        Assert.assertEquals("writer_user writer_group", domain.getWriters());
    }
    TimelineEntities entitiesAttempts = yarnCluster.getApplicationHistoryServer().getTimelineStore()
            .getEntities(ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString(), null, null, null, null, null,
                    null, null, null);
    Assert.assertNotNull(entitiesAttempts);
    Assert.assertEquals(1, entitiesAttempts.getEntities().size());
    Assert.assertEquals(2, entitiesAttempts.getEntities().get(0).getEvents().size());
    Assert.assertEquals(entitiesAttempts.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString());
    if (haveDomain) {
        Assert.assertEquals(domain.getId(), entitiesAttempts.getEntities().get(0).getDomainId());
    } else {
        Assert.assertEquals("DEFAULT", entitiesAttempts.getEntities().get(0).getDomainId());
    }
    TimelineEntities entities = yarnCluster.getApplicationHistoryServer().getTimelineStore().getEntities(
            ApplicationMaster.DSEntity.DS_CONTAINER.toString(), null, null, null, null, null, null, null, null);
    Assert.assertNotNull(entities);
    Assert.assertEquals(2, entities.getEntities().size());
    Assert.assertEquals(entities.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_CONTAINER.toString());
    if (haveDomain) {
        Assert.assertEquals(domain.getId(), entities.getEntities().get(0).getDomainId());
    } else {
        Assert.assertEquals("DEFAULT", entities.getEntities().get(0).getDomainId());
    }
}

From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java

private boolean validateHadoopDir(final Stage.Context context, final String configName,
        final String configGroup, String dirPathTemplate, final List<Stage.ConfigIssue> issues) {
    final AtomicBoolean ok = new AtomicBoolean(true);
    if (!dirPathTemplate.startsWith("/")) {
        issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_40));
        ok.set(false);
    } else {/*from  ww  w . ja v a  2 s  . c  o m*/
        dirPathTemplate = (dirPathTemplate.isEmpty()) ? "/" : dirPathTemplate;
        try {
            final Path dir = new Path(dirPathTemplate);
            final FileSystem fs = getFileSystemForInitDestroy();
            getUGI().doAs(new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    if (!fs.exists(dir)) {
                        try {
                            if (fs.mkdirs(dir)) {
                                ok.set(true);
                            } else {
                                issues.add(
                                        context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_41));
                                ok.set(false);
                            }
                        } catch (IOException ex) {
                            issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_42,
                                    ex.toString()));
                            ok.set(false);
                        }
                    } else {
                        try {
                            Path dummy = new Path(dir, "_sdc-dummy-" + UUID.randomUUID().toString());
                            fs.create(dummy).close();
                            fs.delete(dummy, false);
                            ok.set(true);
                        } catch (IOException ex) {
                            issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_43,
                                    ex.toString()));
                            ok.set(false);
                        }
                    }
                    return null;
                }
            });
        } catch (Exception ex) {
            issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_44, ex.toString()));
            ok.set(false);
        }
    }
    return ok.get();
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldCallFail() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeoutCalled.set(true)).create();
    try {//from w w w. j a va  2  s.com
        gremlinExecutor.eval("10/0").get();
        fail();
    } catch (Exception ignored) {
    }

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertFalse(timeoutCalled.get());
    assertFalse(successCalled.get());
    assertTrue(failureCalled.get());
    gremlinExecutor.close();
}

From source file:com.adaptris.core.ftp.FtpConsumerTest.java

public void testConsumeWithQuietPeriodAndTimezone() throws Exception {
    int count = 1;
    EmbeddedFtpServer helper = new EmbeddedFtpServer();
    MockMessageListener listener = new MockMessageListener(100);
    FileSystem filesystem = helper.createFilesystem_DirsOnly();
    for (int i = 0; i < count; i++) {
        filesystem.add(/*from w w  w. j a  v a 2  s  .  c o  m*/
                new FileEntry(DEFAULT_WORK_DIR_CANONICAL + SLASH + DEFAULT_FILENAME + i + ".txt", PAYLOAD));
    }
    FakeFtpServer server = helper.createAndStart(filesystem);
    StandaloneConsumer sc = null;
    try {

        AtomicBoolean pollFired = new AtomicBoolean(false);
        PollerImp poller = new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS))
                .withPollerCallback(e -> {
                    log.trace("Poll Fired {}", getName());
                    if (e == 0) {
                        pollFired.set(true);
                    }
                });
        FtpConsumer ftpConsumer = createForTests(listener, "testConsumeWithQuietPeriodAndTimezone", poller);

        ftpConsumer.setQuietInterval(new TimeInterval(3L, TimeUnit.SECONDS));
        FtpConnection consumeConnection = create(server);
        consumeConnection.setAdditionalDebug(true);
        consumeConnection.setServerTimezone("America/Los_Angeles");

        sc = new StandaloneConsumer(consumeConnection, ftpConsumer);
        start(sc);
        long waitTime = waitForPollCallback(pollFired);
        log.trace("Waited for {}ms for == 0 poll", waitTime);

        helper.assertMessages(listener.getMessages(), 0);
        assertEquals(count, filesystem.listFiles(DEFAULT_WORK_DIR_CANONICAL).size());

    } catch (Exception e) {
        throw e;
    } finally {
        stop(sc);
        server.stop();
    }
}

From source file:com.qwazr.utils.json.DirectoryJsonManager.java

private T getNoLock(File file, String name, AtomicBoolean mustBeEvaluated) throws IOException {
    Pair<Long, T> item = instancesCache.get(name);
    long lastModified = file.lastModified();
    if (file.exists()) {
        if (item != null && item.getLeft() == lastModified)
            return item.getRight();
        if (mustBeEvaluated == null) {
            item = loadItem(name, file, lastModified);
            buildCache();//from w w w. j av  a2  s  .  c o  m
            return item.getRight();
        }
    } else {
        if (item == null)
            return null;
        if (mustBeEvaluated == null) {
            instancesMap.remove(name);
            buildCache();
            return null;
        }
    }
    mustBeEvaluated.set(true);
    return null;
}