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.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testMultipleThreadsWithElementsRemoved() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);
    final CyclicBarrier barrier = new CyclicBarrier(5);
    final List<Future<Map<Integer, Integer>>> futures = new ArrayList<Future<Map<Integer, Integer>>>();

    for (int i = 0; i < 5; i++) {
        futures.add(threadPool.submit(new Callable<Map<Integer, Integer>>() {

            @Override//from  w  w w. j av  a  2s . c o  m
            public Map<Integer, Integer> call() throws Exception {

                barrier.await();

                TestWorker worker = new TestWorker();

                while (!stop.get()) {
                    worker.process();
                }

                return worker.map;
            }
        }));
    }

    Thread.sleep(200);

    List<Integer> newList = new ArrayList<Integer>(iList);

    final List<Integer> removedElements = new ArrayList<Integer>();
    removedElements.add(newList.remove(2));
    removedElements.add(newList.remove(5));
    removedElements.add(newList.remove(6));

    cList.swapWithList(newList);

    Thread.sleep(200);
    stop.set(true);

    Map<Integer, Integer> result = getTotalMap(futures);

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {

        @Override
        public boolean apply(Integer x) {
            return !removedElements.contains(x);
        }
    });

    checkValues(new ArrayList<Integer>(subMap.values()));
}

From source file:de.willuhn.jameica.hbci.passports.pintan.ChipTANDialog.java

/**
* @see de.willuhn.jameica.gui.dialogs.PasswordDialog#paint(org.eclipse.swt.widgets.Composite)
*///  w  w  w . j a v a2 s .  c  o  m
protected void paint(final Composite parent) throws Exception {
    Container container = new SimpleContainer(parent);

    if (this.usb) {
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Legen Sie die bitte Chipkarte ein."), StatusBarMessage.TYPE_INFO));

        this.setShowPassword(true); // Bei ChipTAN USB immer die TAN anzeigen, damit der User vergleichen kann.
        container.addHeadline(i18n.tr("ChipTAN USB"));
        container.addText(i18n.tr(
                "Legen Sie die Chipkarte ein und folgen Sie den Anweisungen des Kartenlesers. Klicken Sie auf \"OK\", wenn die TAN korrekt bertragen wurde."),
                true);

        ProgressBar progress = new ProgressBar(container.getComposite(), SWT.INDETERMINATE);
        final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = 2;
        progress.setLayoutData(gd);

        final AtomicBoolean cancelled = new AtomicBoolean(false);

        final Thread usbThread = new Thread() {
            public void run() {
                try {
                    Logger.info("trying to get TAN using USB cardreader");
                    String s = StringUtils.trimToNull(service.getTan(code));
                    if (s != null && !cancelled.get()) {
                        setPassword(s, parent);
                    } else {
                        throw new Exception(i18n.tr("Keine TAN bertragen"));
                    }
                } catch (Exception e) {
                    if (!cancelled.get()) {
                        Logger.error("unable to get tan from chipcard", e);
                        setErrorText(i18n.tr("Fehler bei TAN-Ermittlung: {0}", e.getMessage()));
                    }
                }
            }
        };
        usbThread.start();

        parent.addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent e) {
                cancelled.set(true);
                // Nur fuer den Fall, dass der Thread noch laeuft.
                try {
                    if (usbThread != null)
                        usbThread.interrupt();
                } catch (Throwable th) {
                    Logger.error("unable to interrupt USB thread", th);
                }
            }
        });
    } else {
        container.addHeadline(i18n.tr(this.usb ? "ChipTAN USB" : "Flicker-Grafik"));
        container.addText(i18n.tr("Klicken Sie \"-\" bzw. \"+\", um die Breite anzupassen."), true);
        FlickerPart flicker = new FlickerPart(this.code);
        flicker.paint(parent);
    }

    // Hier stehen dann noch die Anweisungen von der Bank drin
    super.paint(parent);

    if (!this.usb) {
        // Wir muessen das Fenster wenigstens gross genug machen, damit der Flickercode reinpasst, falls
        // der User den recht verbreitert hat
        int width = settings.getInt("width", -1);
        if (width > 0)
            width += 10; // Wenigstens noch 10 Pixel Rand hinzufuegen.
        // Wir nehmen den groesseren von beiden Werten

        getShell().setMinimumSize(getShell().computeSize(width > WINDOW_WIDTH ? width : WINDOW_WIDTH,
                smallDisplay ? 520 : SWT.DEFAULT));
    }
}

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

public void scan() {
    WebTarget t = extractWebTarget(dockerScanner.getDockerClient());
    logger.info("Scanning {}", t);
    JsonNode response = t.path("/info").request().buildGet().invoke(JsonNode.class);

    JsonNode swarm = response.path("Swarm");
    JsonNode cluster = swarm.path("Cluster");
    String swarmClusterId = cluster.path("ID").asText();

    // need to parse these dates
    String createdAt = cluster.path("CreatedAt").asText();
    String updatedAt = cluster.path("UpdatedAt").asText();
    ObjectNode props = mapper.createObjectNode();
    props.put("swarmClusterId", swarmClusterId);
    props.put("createdAt", createdAt);
    props.put("updatedAt", updatedAt);

    JsonNode swarmNode = dockerScanner.getNeoRxClient().execCypher(
            "merge (c:DockerSwarm {swarmClusterId:{id}}) set c+={props},c.updateTs=timestamp() return c", "id",
            swarmClusterId, "props", props).blockingFirst(MissingNode.getInstance());

    if (isUnixDomainScoket(t.getUri().toString())) {
        // Only set managerApiUrl to a unix domain socket if it has not
        // already been set.
        // This is useful for trident
        if (!isUnixDomainScoket(swarmNode.path("managerApiUrl").asText())) {

            String LOCAL_DOCKER_DAEMON_SOCKET_URL = "unix:///var/run/docker.sock";
            logger.info("setting mangerApiUrl to {} for swarm {}", LOCAL_DOCKER_DAEMON_SOCKET_URL,
                    swarmClusterId);//from w  w w  .  j a  v  a  2s  .co  m

            String name = "local";
            dockerScanner.getNeoRxClient()
                    .execCypher("match (c:DockerSwarm {name:{name}}) return c", "name", name).forEach(it -> {
                        String oldSwarmClusterId = it.path("swarmClusterId").asText();
                        if (!swarmClusterId.equals(oldSwarmClusterId)) {
                            dockerScanner.getNeoRxClient().execCypher(
                                    "match (c:DockerSwarm {swarmClusterId:{swarmClusterId}}) detach delete c",
                                    "swarmClusterId", oldSwarmClusterId);
                        }
                    });

            dockerScanner.getNeoRxClient().execCypher(
                    "match (c:DockerSwarm {swarmClusterId:{id}}) set c.managerApiUrl={managerApiUrl},c.name={name},c.tridentClusterId={name} return c",
                    "id", swarmClusterId, "managerApiUrl", LOCAL_DOCKER_DAEMON_SOCKET_URL, "name", name);

        }
    }

    AtomicBoolean fail = new AtomicBoolean(false);
    response = t.path("/nodes").request().buildGet().invoke(JsonNode.class);
    AtomicLong earliestTimestamp = new AtomicLong(Long.MAX_VALUE);
    response.elements().forEachRemaining(it -> {
        try {
            earliestTimestamp.set(
                    Math.min(earliestTimestamp.get(), saveDockerNode(swarmClusterId, flattenSwarmNode(it))));
        } catch (RuntimeException e) {
            logger.warn("problem", e);
            fail.set(true);
        }
    });

    if (!fail.get()) {
        if (earliestTimestamp.get() < System.currentTimeMillis()) {
            logger.info("deleting DockerHost nodes before with updateTs<{}", earliestTimestamp.get());
            dockerScanner.getNeoRxClient().execCypher(
                    "match (s:DockerSwarm {swarmClusterId:{id}})--(x:DockerHost) where s.updateTs>x.updateTs detach delete x",
                    "id", swarmClusterId);
        }
    }
    scanServicesForSwarm(swarmClusterId);
    scanTasksForSwarm(swarmClusterId);
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public Path download(ChromiumVersion version) {
    final Path destinationRoot = getChromiumPath(version);
    final Path executable = getExecutable(version);

    String url;//from  ww w .  ja  v a 2 s  .  c o  m
    if (WINDOWS) {
        url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (LINUX) {
        url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (MAC) {
        url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision());
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("HEAD");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }
        long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0);
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r"
                + version.getRevision() + ".zip";
        Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName);
        if (exists(archive) && contentLength != size(archive)) {
            delete(archive);
        }
        if (!exists(archive)) {
            logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%");
            u = new URL(url);
            if (conn.getResponseCode() != 200) {
                throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            Thread thread = null;
            AtomicBoolean halt = new AtomicBoolean(false);
            Runnable progress = () -> {
                try {
                    long fileSize = size(archive);
                    logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(),
                            round((fileSize * 100L) / contentLength));
                } catch (IOException e) {
                    // ignore
                }
            };
            try (InputStream is = conn.getInputStream()) {
                logger.info("Download location: " + archive.toString());
                thread = new Thread(() -> {
                    while (true) {
                        try {
                            if (halt.get()) {
                                break;
                            }
                            progress.run();
                            sleep(1000);
                        } catch (Throwable e) {
                            // ignore
                        }
                    }
                });
                thread.setName("cdp4j");
                thread.setDaemon(true);
                thread.start();
                copy(conn.getInputStream(), archive);
            } finally {
                if (thread != null) {
                    progress.run();
                    halt.set(true);
                }
            }
        }
        logger.info("Extracting to: " + destinationRoot.toString());
        if (exists(archive)) {
            createDirectories(destinationRoot);
            unpack(archive.toFile(), destinationRoot.toFile());
        }

        if (!exists(executable) || !isExecutable(executable)) {
            throw new CdpException("Chromium executable not found: " + executable.toString());
        }

        if (!WINDOWS) {
            Set<PosixFilePermission> permissions = getPosixFilePermissions(executable);
            if (!permissions.contains(OWNER_EXECUTE)) {
                permissions.add(OWNER_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
            if (!permissions.contains(GROUP_EXECUTE)) {
                permissions.add(GROUP_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
        }
    } catch (IOException e) {
        throw new CdpException(e);
    }
    return executable;
}

From source file:com.ebay.jetstream.messaging.transport.zookeeper.ZooKeeperTransport.java

public ZooKeeperTransport() {
    m_queueStats = new DispatchQueueStats();
    m_initialized = new AtomicBoolean(false);
    m_shutdown = new AtomicBoolean(false);
}

From source file:gobblin.runtime.Task.java

/**
 * Instantiate a new {@link Task}./* www .j av a 2s  .co m*/
 *
 * @param context a {@link TaskContext} containing all necessary information to construct and run a {@link Task}
 * @param taskStateTracker a {@link TaskStateTracker} for tracking task state
 * @param taskExecutor a {@link TaskExecutor} for executing the {@link Task} and its {@link Fork}s
 * @param countDownLatch an optional {@link java.util.concurrent.CountDownLatch} used to signal the task completion
 */
public Task(TaskContext context, TaskStateTracker taskStateTracker, TaskExecutor taskExecutor,
        Optional<CountDownLatch> countDownLatch) {
    this.taskContext = context;
    this.taskState = context.getTaskState();
    this.jobId = this.taskState.getJobId();
    this.taskId = this.taskState.getTaskId();
    this.taskKey = this.taskState.getTaskKey();
    this.taskStateTracker = taskStateTracker;
    this.taskExecutor = taskExecutor;
    this.countDownLatch = countDownLatch;
    this.closer = Closer.create();
    this.closer.register(this.taskState.getTaskBrokerNullable());
    this.extractor = closer
            .register(new InstrumentedExtractorDecorator<>(this.taskState, this.taskContext.getExtractor()));

    this.converter = closer.register(new MultiConverter(this.taskContext.getConverters()));
    try {
        this.rowChecker = closer.register(this.taskContext.getRowLevelPolicyChecker());
    } catch (Exception e) {
        try {
            closer.close();
        } catch (Throwable t) {
            LOG.error("Failed to close all open resources", t);
        }
        throw new RuntimeException("Failed to instantiate row checker.", e);
    }

    this.taskMode = getExecutionModel(this.taskState);
    this.recordsPulled = new AtomicLong(0);
    this.lastRecordPulledTimestampMillis = 0;
    this.shutdownRequested = new AtomicBoolean(false);
    this.shutdownLatch = new CountDownLatch(1);

    // Setup Streaming constructs

    this.watermarkingStrategy = "FineGrain"; // TODO: Configure

    if (isStreamingTask()) {
        Extractor underlyingExtractor = this.taskContext.getRawSourceExtractor();
        if (!(underlyingExtractor instanceof StreamingExtractor)) {
            LOG.error(
                    "Extractor {}  is not an instance of StreamingExtractor but the task is configured to run in continuous mode",
                    underlyingExtractor.getClass().getName());
            throw new TaskInstantiationException("Extraction " + underlyingExtractor.getClass().getName()
                    + " is not an instance of StreamingExtractor but the task is configured to run in continuous mode");
        }

        this.watermarkStorage = Optional.of(taskContext.getWatermarkStorage());
        Config config;
        try {
            config = ConfigUtils.propertiesToConfig(taskState.getProperties());
        } catch (Exception e) {
            LOG.warn("Failed to deserialize taskState into Config.. continuing with an empty config", e);
            config = ConfigFactory.empty();
        }

        long commitIntervalMillis = ConfigUtils.getLong(config,
                TaskConfigurationKeys.STREAMING_WATERMARK_COMMIT_INTERVAL_MILLIS,
                TaskConfigurationKeys.DEFAULT_STREAMING_WATERMARK_COMMIT_INTERVAL_MILLIS);
        if (watermarkingStrategy.equals("FineGrain")) { // TODO: Configure
            this.watermarkTracker = Optional.of(this.closer.register(new FineGrainedWatermarkTracker(config)));
            this.watermarkManager = Optional.of((WatermarkManager) this.closer
                    .register(new TrackerBasedWatermarkManager(this.watermarkStorage.get(),
                            this.watermarkTracker.get(), commitIntervalMillis, Optional.of(this.LOG))));

        } else {
            // writer-based watermarking
            this.watermarkManager = Optional
                    .of((WatermarkManager) this.closer.register(new MultiWriterWatermarkManager(
                            this.watermarkStorage.get(), commitIntervalMillis, Optional.of(this.LOG))));
            this.watermarkTracker = Optional.absent();
        }
    } else {
        this.watermarkManager = Optional.absent();
        this.watermarkTracker = Optional.absent();
        this.watermarkStorage = Optional.absent();
    }
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

@Test
public void callerSuppliedChecksum() throws IOException, SignatureException, XmlProcessingException {
    final String bucketName = "caller_supplied_checksum_test";

    try {// w  w w .  jav  a  2s. com
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object("beowulf.txt", 294059));
        final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(bucketName, objs,
                WriteJobOptions.create().withChecksumType(ChecksumType.Type.MD5));

        final AtomicBoolean callbackCalled = new AtomicBoolean(false);

        job.withChecksum(new ChecksumFunction() {
            @Override
            public String compute(final BulkObject obj, final ByteChannel channel) {
                if (obj.getName().equals("beowulf.txt")) {
                    callbackCalled.set(true);
                    return "rCu751L6xhB5zyL+soa3fg==";
                }
                return null;
            }
        });

        final SingleChecksumListener listener = new SingleChecksumListener();

        job.attachChecksumListener(listener);

        job.transfer(new ResourceObjectPutter("books/"));

        final String checksum = listener.getChecksum();

        assertThat(checksum, is(notNullValue()));
        assertThat(checksum, is("rCu751L6xhB5zyL+soa3fg=="));
        assertTrue(callbackCalled.get());

    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}

From source file:com.ebay.jetstream.messaging.transport.zookeeper.ZooKeeperTransport.java

public ZooKeeperTransport(String addr, int port, ITransportListener tl) {
    m_queueStats = new DispatchQueueStats();
    m_initialized = new AtomicBoolean(false);
    m_shutdown = new AtomicBoolean(false);
    this.m_addr = null;
    this.m_addr = addr;
    this.m_port = port;
    m_transportListener = tl;//from w w  w  .j  a v a2  s  .c  o  m
}

From source file:io.druid.segment.realtime.plumber.RealtimePlumberSchoolTest.java

@Test(timeout = 60000)
public void testPersistFails() throws Exception {
    final AtomicBoolean committed = new AtomicBoolean(false);
    plumber.getSinks().put(0L, new Sink(new Interval(0, TimeUnit.HOURS.toMillis(1)), schema, tuningConfig,
            new DateTime("2014-12-01T12:34:56.789").toString()));
    plumber.startJob();/*w  ww  . j a v a  2s .c o m*/
    final InputRow row = EasyMock.createNiceMock(InputRow.class);
    EasyMock.expect(row.getTimestampFromEpoch()).andReturn(0L);
    EasyMock.expect(row.getDimensions()).andReturn(new ArrayList<String>());
    EasyMock.replay(row);
    plumber.add(row, Committers.supplierOf(Committers.nil()));
    plumber.persist(Committers.supplierFromRunnable(new Runnable() {
        @Override
        public void run() {
            committed.set(true);
            throw new RuntimeException();
        }
    }).get());
    while (!committed.get()) {
        Thread.sleep(100);
    }

    // Exception may need time to propagate
    while (metrics.failedPersists() < 1) {
        Thread.sleep(100);
    }

    Assert.assertEquals(1, metrics.failedPersists());
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@Test
@SuppressWarnings("SleepWhileInLoop")
public void testSynchingLogic() throws InterruptedException {
    long sleeptime = 25L;
    final ArrayList<Object> list = new ArrayList<Object>();
    GenericOperator go = new GenericOperator();
    final GenericNode gn = new GenericNode(go,
            new com.datatorrent.stram.engine.OperatorContext(0, new DefaultAttributeMap(), null));
    gn.setId(1);// w w  w .  j  ava  2  s. co  m
    AbstractReservoir reservoir1 = AbstractReservoir.newReservoir("ip1Res", 1024);
    AbstractReservoir reservoir2 = AbstractReservoir.newReservoir("ip2Res", 1024);
    Sink<Object> output = new Sink<Object>() {
        @Override
        public void put(Object tuple) {
            list.add(tuple);
        }

        @Override
        public int getCount(boolean reset) {
            return 0;
        }

    };

    gn.connectInputPort("ip1", reservoir1);
    gn.connectInputPort("ip2", reservoir2);
    gn.connectOutputPort("op", output);
    gn.firstWindowMillis = 0;
    gn.windowWidthMillis = 100;

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            gn.activate();
            gn.run();
            gn.deactivate();
        }

    };
    t.start();

    do {
        Thread.sleep(sleeptime);
    } while (ab.get() == false);

    Tuple beginWindow1 = new Tuple(MessageType.BEGIN_WINDOW, 0x1L);

    reservoir1.add(beginWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    reservoir2.add(beginWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    Tuple endWindow1 = new EndWindowTuple(0x1L);

    reservoir1.add(endWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    Tuple beginWindow2 = new Tuple(MessageType.BEGIN_WINDOW, 0x2L);

    reservoir1.add(beginWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    reservoir2.add(endWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    reservoir2.add(beginWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    Tuple endWindow2 = new EndWindowTuple(0x2L);

    reservoir2.add(endWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    reservoir1.add(endWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(4, list.size());

    EndStreamTuple est = new EndStreamTuple(0L);

    reservoir1.add(est);
    Thread.sleep(sleeptime);
    Assert.assertEquals(4, list.size());

    Tuple beginWindow3 = new Tuple(MessageType.BEGIN_WINDOW, 0x3L);

    reservoir2.add(beginWindow3);
    Thread.sleep(sleeptime);
    Assert.assertEquals(5, list.size());

    Tuple endWindow3 = new EndWindowTuple(0x3L);

    reservoir2.add(endWindow3);
    Thread.sleep(sleeptime);
    Assert.assertEquals(6, list.size());

    Assert.assertNotSame(Thread.State.TERMINATED, t.getState());

    reservoir2.add(est);
    Thread.sleep(sleeptime);
    Assert.assertEquals(7, list.size());

    Thread.sleep(sleeptime);

    Assert.assertEquals(Thread.State.TERMINATED, t.getState());
}