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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {/*from   w  w w.j a  v  a  2 s.c  o  m*/
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();

                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server = new TestingServer(server.getPort(), server.getTempDirectory());
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:de.tbuchloh.kiskis.cracker.PasswordCracker.java

public String crackPassword() {
    final Long totalEstimation = _passwordCreator.estimateTotalCount();
    _progressListener.notifyTotalCount(totalEstimation);
    _progressListener.notifyStartTime(System.currentTimeMillis());

    final AtomicBoolean found = new AtomicBoolean(false);
    final Callable<String> callable = new Callable<String>() {

        @Override/*from w  w w .j  a v a2s  .c o m*/
        public String call() throws Exception {
            String guess;
            while (!found.get() && (guess = _passwordCreator.create()) != null) {
                _progressListener.notifyTry(guess);
                if (_tester.test(guess)) {
                    found.set(true);
                    return guess;
                }
            }
            return null;
        }
    };

    final int cpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    LOG.info(String.format("Found %1$d cpus ...", cpus));
    final ExecutorService threadPool = Executors.newFixedThreadPool(cpus);
    final Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();
    for (int i = 0; i < cpus; ++i) {
        tasks.add(callable);
    }
    try {
        final List<Future<String>> futures = threadPool.invokeAll(tasks);
        for (final Future<String> future : futures) {
            final String guessedPwd = future.get();
            if (guessedPwd != null) {
                return guessedPwd;
            }
        }
        return null;
    } catch (final InterruptedException e) {
        throw new KisKisRuntimeException("InterruptedException", e);
    } catch (final ExecutionException e) {
        throw new KisKisRuntimeException("ExecutionException", e);
    }
}

From source file:com.moosemorals.mediabrowser.FtpScanner.java

FtpScanner(PVR pvr, String remoteHostname) {
    this.pvr = pvr;
    this.remoteHostname = remoteHostname;

    FTPClientConfig config = new FTPClientConfig();
    config.setServerTimeZoneId(DEFAULT_TIMEZONE.getID());
    config.setServerLanguageCode("EN");

    ftp = new FTPClient();
    ftp.configure(config);/*from w ww.  ja  va  2  s.  co  m*/
    if (debugFTP) {
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    }
    ftpRunning = new AtomicBoolean(false);

}

From source file:com.alibaba.jstorm.message.netty.NettyClientAsync.java

@SuppressWarnings("rawtypes")
NettyClientAsync(Map storm_conf, ChannelFactory factory, ScheduledExecutorService scheduler, String host,
        int port, ReconnectRunnable reconnector) {
    super(storm_conf, factory, scheduler, host, port, reconnector);

    BATCH_THREASHOLD_WARN = ConfigExtension.getNettyBufferThresholdSize(storm_conf);
    blockSend = isBlockSend(storm_conf);
    directlySend = isDirectSend(storm_conf);

    flush_later = new AtomicBoolean(false);
    flushCheckInterval = Utils.getInt(storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

    Runnable flusher = new Runnable() {
        @Override// ww w.ja  v  a2  s.c  om
        public void run() {
            flush();
        }
    };
    long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
    scheduler.scheduleAtFixedRate(flusher, initialDelay, flushCheckInterval, TimeUnit.MILLISECONDS);

    clientChannelFactory = factory;

    start();
    LOG.info(this.toString());
}

From source file:com.jayway.restassured.path.json.JsonPathObjectDeserializationTest.java

@Test
public void json_path_supports_custom_deserializer_with_static_configuration() {
    // Given//from  w  w w  .j av  a 2s. co m
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    JsonPath.config = new JsonPathConfig().defaultObjectDeserializer(new JsonPathObjectDeserializer() {
        public <T> T deserialize(ObjectDeserializationContext ctx) {
            customDeserializerUsed.set(true);
            final String json = ctx.getDataToDeserialize().asString();
            final Greeting greeting = new Greeting();
            greeting.setFirstName(StringUtils.substringBetween(json, "\"firstName\":\"", "\""));
            greeting.setLastName(StringUtils.substringBetween(json, "\"lastName\":\"", "\""));
            return (T) greeting;
        }
    });

    final JsonPath jsonPath = new JsonPath(GREETING);

    // When
    try {
        final Greeting greeting = jsonPath.getObject("", Greeting.class);

        // Then
        assertThat(greeting.getFirstName(), equalTo("John"));
        assertThat(greeting.getLastName(), equalTo("Doe"));
        assertThat(customDeserializerUsed.get(), is(true));
    } finally {
        JsonPath.reset();
    }
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java

public DefaultNetWorkClient(String hostName, int port) {
    this.hostName = hostName;
    this.port = port;
    state = new AtomicInteger(NetworkStateEnum.NETWORK_STATE_DISCONNECT.value);
    isWeakuped = new AtomicBoolean(false);
    inputBuffer = new LinkedBlockingQueue<ByteBuffer>();
    outputBuffer = new LinkedBlockingQueue<Command>();
    waitMoreDataLock = new byte[0];
}

From source file:com.facebook.buck.artifact_cache.ArtifactUploaderTest.java

@Test
public void testPerformUploadToArtifactCache() throws IOException {

    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();

    byte[] contents = "contents".getBytes();

    Path file = Paths.get("file");
    filesystem.writeBytesToPath(contents, file);

    Path dirFile = Paths.get("dir", "file");
    filesystem.createParentDirs(dirFile);
    filesystem.writeBytesToPath(contents, dirFile);

    Path metadataFile = Paths.get("buck-out", "bin", "foo", ".bar", "metadata", "artifact", "metadata");
    filesystem.createParentDirs(metadataFile);
    filesystem.writeBytesToPath(contents, metadataFile);

    Path dir = Paths.get("buck-out", "bin", "foo", ".bar/");
    filesystem.mkdirs(dir);/*  ww  w .j  a v a2  s .  c om*/

    AtomicBoolean stored = new AtomicBoolean(false);
    ArtifactCache cache = new NoopArtifactCache() {
        @Override
        public CacheReadMode getCacheReadMode() {
            return CacheReadMode.READWRITE;
        }

        @Override
        public ListenableFuture<Void> store(ArtifactInfo info, BorrowablePath output) {
            stored.set(true);

            // Verify the build metadata.
            assertThat(info.getMetadata().get("build-metadata"), Matchers.equalTo("build-metadata"));

            // Unarchive file.
            final ImmutableMap<String, byte[]> archiveContents;
            try {
                archiveContents = TarInspector.readTarZst(output.getPath());
            } catch (IOException | CompressorException e) {
                fail(e.getMessage());
                return Futures.immediateFuture(null);
            }

            // Verify archive contents.
            assertEquals(ImmutableSet.of("buck-out/bin/foo/.bar/", "dir/file", "file",
                    "buck-out/bin/foo/.bar/metadata/artifact/metadata"), archiveContents.keySet());
            assertArrayEquals(contents, archiveContents.get("file"));
            assertArrayEquals(contents, archiveContents.get("dir/file"));
            assertArrayEquals(contents,
                    archiveContents.get("buck-out/bin/foo/.bar/metadata/artifact/metadata"));
            return Futures.immediateFuture(null);
        }
    };

    ArtifactUploader.performUploadToArtifactCache(ImmutableSet.of(new RuleKey("aa")), cache,
            BuckEventBusForTests.newInstance(),
            ImmutableMap.of("metadata", "metadata", "build-metadata", "build-metadata"),
            ImmutableSortedSet.of(dir, file, dirFile, metadataFile), BUILD_TARGET, filesystem, 1000);

    assertTrue(stored.get());
}

From source file:com.twitter.hbc.httpclient.BasicClient.java

/**
 * For testing only/*w  ww  .j av a 2s .  com*/
 */
@VisibleForTesting
BasicClient(final ClientBase clientBase, ExecutorService executorService) {
    this.canRun = new AtomicBoolean(true);
    this.clientBase = clientBase;
    this.executorService = executorService;
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.JvmMetricSet.java

public JvmMetricSet() {
    this.runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.bufferPoolMetricSet = new BufferPoolMetricSet();
    metricsByNames.put("bufferPools", bufferPoolMetricSet);

    this.classLoadingMetricSet = new ClassLoadingMetricSet();
    metricsByNames.put("classes", classLoadingMetricSet);

    this.threadMetricSet = new ThreadMetricSet();
    metricsByNames.put("threads", threadMetricSet);

    this.memoryMetricSet = new JvmMemoryMetricSet();
    metricsByNames.put("memory", memoryMetricSet);

    this.gcMetricSet = new GarbageCollectorMetricSet();
    metricsByNames.put("gc", gcMetricSet);

    this.uptimeInMillisGauge = new Gauge<Long>() {
        @Override//from   www .ja  v a2 s. c  om
        public Long getValue() {
            return runtimeMXBean.getUptime();
        }
    };
    metricsByNames.put("uptimeInMillis", uptimeInMillisGauge);

    this.metricsByNames = metricsByNames;

    this.shutdown = new AtomicBoolean(false);
}

From source file:com.olacabs.fabric.compute.sources.kafka.impl.KafkaReaderLeaderElector.java

public void start() throws Exception {
    readers.keySet().forEach(partiton -> {
        isRunning.put(partiton, new AtomicBoolean(false));
    });/* w w  w.j a  v  a 2s .c  o  m*/
    scheduler.scheduleWithFixedDelay(() -> {
        LOGGER.debug("Checking zookeeper");
        try {
            readers.keySet().forEach(partiton -> {
                try {
                    final String communicatorPath = communicatorPath(partiton);
                    byte[] data = curatorFramework.getData().forPath(communicatorPath);
                    final String selectedReader = new String(data);
                    if (readerId.equals(selectedReader)) {
                        if (isRunning.get(partiton).compareAndSet(false, true)) {
                            LOGGER.info("[{}:{}:{}] Got start", topology, topic, partiton);
                            executorService.submit(readers.get(partiton));
                        } else {
                            LOGGER.debug("[{}:{}:{}] Nothing changed .. already running...", topology, topic,
                                    partiton);
                        }
                    } else {
                        if (isRunning.get(partiton).compareAndSet(true, false)) {
                            LOGGER.info("[{}:{}:{}] Got stop", topology, topic, partiton);
                            readers.get(partiton).stop();
                        } else {
                            LOGGER.debug("[{}:{}:{}] Nothing changed .. already stopped...", topology, topic,
                                    partiton);
                        }
                    }
                } catch (KeeperException.NoNodeException e) {
                    LOGGER.info("[{}:{}:{}] Communicator not yet initialized", topology, topic, partiton);
                } catch (Throwable e) {
                    LOGGER.error("[{}:{}:{}] Error reading ZK node for reader id", topology, topic, partiton);
                    throw new RuntimeException(e);
                }
            });
            peerCountChange();
        } catch (Throwable t) {
            LOGGER.info("Error detecting membership changes.", t);
        }
    }, 0, 10, TimeUnit.SECONDS);
    LOGGER.info("[{}:{}:{}] Creating communicators", topology, topic, memberPathPrefix());
    LOGGER.info("[{}:{}:{}] Watching reader path: {}", topology, topic, memberPathPrefix());
    final String leaderPath = String.format("/%s/%s/loadbalancer-leader", topology, topic);
    this.leaderSelector = new LeaderSelector(curatorFramework, leaderPath, this);
    LOGGER.info("Starting leader selector at: " + leaderPath);
    curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL)
            .forPath(memberPath());
    LOGGER.info("Member path created at: " + memberPath());
    leaderSelector.start();
}