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

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

Introduction

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

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

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

@Test
public void testPrematureTermination() throws InterruptedException {
    long maxSleep = 5000;
    long sleeptime = 25L;
    GenericOperator go = new GenericOperator();
    final GenericNode gn = new GenericNode(go,
            new com.datatorrent.stram.engine.OperatorContext(0, new DefaultAttributeMap(), null));
    gn.setId(1);//w  ww.  j a  v  a2 s  .co m
    AbstractReservoir reservoir1 = AbstractReservoir.newReservoir("ip1Res", 1024);
    AbstractReservoir reservoir2 = AbstractReservoir.newReservoir("ip2Res", 1024);

    gn.connectInputPort("ip1", reservoir1);
    gn.connectInputPort("ip2", reservoir2);
    gn.connectOutputPort("op", Sink.BLACKHOLE);
    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();

    long interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((ab.get() == false) && (interval < maxSleep));

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

    reservoir1.add(beginWindow1);
    reservoir2.add(beginWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("Begin window called", go.endWindowId != go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

    Tuple endWindow1 = new EndWindowTuple(0x1L);

    reservoir1.add(endWindow1);
    reservoir2.add(endWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("End window called", go.endWindowId == go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

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

    reservoir1.add(beginWindow2);
    reservoir2.add(beginWindow2);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));

    gn.shutdown();
    t.join();

    Assert.assertTrue("End window not called", go.endWindowId != go.beginWindowId);
}

From source file:org.apache.solr.handler.dataimport.processor.XPathEntityProcessor.java

private Iterator<Map<String, Object>> getRowIterator(final Reader data, final String s) {
    //nothing atomic about it. I just needed a StongReference
    final AtomicReference<Exception> exp = new AtomicReference<Exception>();
    final BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<Map<String, Object>>(
            blockingQueueSize);/* w w w . j  a va  2 s .co m*/
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    final AtomicBoolean throwExp = new AtomicBoolean(true);
    publisherThread = new Thread() {
        @Override
        public void run() {
            try {
                xpathReader.streamRecords(data, new XPathRecordReader.Handler() {
                    @Override
                    @SuppressWarnings("unchecked")
                    public void handle(Map<String, Object> record, String xpath) {
                        if (isEnd.get()) {
                            throwExp.set(false);
                            //To end the streaming . otherwise the parsing will go on forever
                            //though consumer has gone away
                            throw new RuntimeException("BREAK");
                        }
                        Map<String, Object> row;
                        try {
                            row = readRow(record, xpath);
                        } catch (final Exception e) {
                            isEnd.set(true);
                            return;
                        }
                        offer(row);
                    }
                });
            } catch (final Exception e) {
                if (throwExp.get())
                    exp.set(e);
            } finally {
                closeIt(data);
                if (!isEnd.get()) {
                    offer(END_MARKER);
                }
            }
        }

        private void offer(Map<String, Object> row) {
            try {
                while (!blockingQueue.offer(row, blockingQueueTimeOut, blockingQueueTimeOutUnits)) {
                    if (isEnd.get())
                        return;
                    LOG.debug("Timeout elapsed writing records.  Perhaps buffer size should be increased.");
                }
            } catch (final InterruptedException e) {
                return;
            } finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        }
    };

    publisherThread.start();

    return new Iterator<Map<String, Object>>() {
        private Map<String, Object> lastRow;
        int count = 0;

        @Override
        public boolean hasNext() {
            return !isEnd.get();
        }

        @Override
        public Map<String, Object> next() {
            Map<String, Object> row;

            do {
                try {
                    row = blockingQueue.poll(blockingQueueTimeOut, blockingQueueTimeOutUnits);
                    if (row == null) {
                        LOG.debug("Timeout elapsed reading records.");
                    }
                } catch (final InterruptedException e) {
                    LOG.debug("Caught InterruptedException while waiting for row.  Aborting.");
                    isEnd.set(true);
                    return null;
                }
            } while (row == null);

            if (row == END_MARKER) {
                isEnd.set(true);
                if (exp.get() != null) {
                    String msg = "Parsing failed for xml, url:" + s + " rows processed in this xml:" + count;
                    if (lastRow != null)
                        msg += " last row in this xml:" + lastRow;
                    if (ABORT.equals(onError)) {
                        wrapAndThrow(SEVERE, exp.get(), msg);
                    } else if (SKIP.equals(onError)) {
                        wrapAndThrow(DataImportHandlerException.SKIP, exp.get());
                    } else {
                        LOG.warn(msg, exp.get());
                    }
                }
                return null;
            }
            count++;
            return lastRow = row;
        }

        @Override
        public void remove() {
            /*no op*/
        }
    };

}

From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java

@Test
public void testCancelReduceTaskWhileSorting() {
    addInputComparator(this.comparator);
    setOutput(new NirvanaOutputList());
    getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);

    final GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>();

    try {//from  w w w .  j a  v  a  2s.c om
        addInputSorted(new DelayingInfinitiveInputIterator(100), this.comparator.duplicate());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }

    final AtomicBoolean success = new AtomicBoolean(false);

    Thread taskRunner = new Thread() {
        @Override
        public void run() {
            try {
                testDriver(testTask, MockReduceStub.class);
                success.set(true);
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

    Assert.assertTrue("Test threw an exception even though it was properly canceled.", success.get());
}

From source file:com.yahoo.sql4d.indexeragent.sql.DBAccessor.java

/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params//www  . j  a v  a 2 s . co  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(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}

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 w w  w  .  jav 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.jayway.restassured.path.json.JsonPathObjectDeserializationTest.java

@Test
public void json_path_supports_custom_deserializer() {
    // Given/*  ww w. j a  v a2s  . co m*/
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    final JsonPath jsonPath = new JsonPath(GREETING)
            .using(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;
                }
            }));

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

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

From source file:org.apache.hadoop.yarn.client.TestAMRMClientAsync.java

@Test(timeout = 10000)
public void testAMRMClientAsync() throws Exception {
    Configuration conf = new Configuration();
    List<ContainerStatus> completed1 = Arrays.asList(BuilderUtils
            .newContainerStatus(BuilderUtils.newContainerId(0, 0, 0, 0), ContainerState.COMPLETE, "", 0));
    List<Container> allocated1 = Arrays.asList(BuilderUtils.newContainer(null, null, null, null, null, null));
    final AllocateResponse response1 = createAllocateResponse(new ArrayList<ContainerStatus>(), allocated1);
    final AllocateResponse response2 = createAllocateResponse(completed1, new ArrayList<Container>());
    final AllocateResponse emptyResponse = createAllocateResponse(new ArrayList<ContainerStatus>(),
            new ArrayList<Container>());

    TestCallbackHandler callbackHandler = new TestCallbackHandler();
    AMRMClient client = mock(AMRMClient.class);
    final AtomicBoolean secondHeartbeatReceived = new AtomicBoolean(false);
    when(client.allocate(anyFloat())).thenReturn(response1).thenAnswer(new Answer<AllocateResponse>() {
        @Override/*ww  w.  j  a v  a  2s.  c  om*/
        public AllocateResponse answer(InvocationOnMock invocation) throws Throwable {
            secondHeartbeatReceived.set(true);
            return response2;
        }
    }).thenReturn(emptyResponse);
    when(client.registerApplicationMaster(anyString(), anyInt(), anyString())).thenReturn(null);

    AMRMClientAsync asyncClient = new AMRMClientAsync(client, 20, callbackHandler);
    asyncClient.init(conf);
    asyncClient.start();
    asyncClient.registerApplicationMaster("localhost", 1234, null);

    // while the CallbackHandler will still only be processing the first response,
    // heartbeater thread should still be sending heartbeats.
    // To test this, wait for the second heartbeat to be received. 
    while (!secondHeartbeatReceived.get()) {
        Thread.sleep(10);
    }

    // allocated containers should come before completed containers
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());

    // wait for the allocated containers from the first heartbeat's response
    while (callbackHandler.takeAllocatedContainers() == null) {
        Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
        Thread.sleep(10);
    }

    // wait for the completed containers from the second heartbeat's response
    while (callbackHandler.takeCompletedContainers() == null) {
        Thread.sleep(10);
    }

    asyncClient.stop();

    Assert.assertEquals(null, callbackHandler.takeAllocatedContainers());
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/* w  w w  . j a v  a2  s  .  c o m*/
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}

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//from  www. j  a  v a 2s. 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.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

/**
 * Get the credentials associated with the authId and the given type.
 * If type is null, all credentials associated with the authId are returned (as JsonArray inside the return value).
 *
 * @param tenantId The id of the tenant the credentials belong to.
 * @param authId The authentication identifier to look up credentials for.
 * @param type The type of credentials to look up.
 * @return The credentials object of the given type or {@code null} if no matching credentials exist.
 *///from  ww  w .  j  a v a 2 s.  com
private JsonObject getSingleCredentials(final String tenantId, final String authId, final String type,
        final JsonObject clientContext) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(type);

    final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
    if (credentialsForTenant != null) {
        final JsonArray authIdCredentials = credentialsForTenant.get(authId);
        if (authIdCredentials != null) {
            for (final Object authIdCredentialEntry : authIdCredentials) {
                final JsonObject authIdCredential = (JsonObject) authIdCredentialEntry;
                // return the first matching type entry for this authId
                if (type.equals(authIdCredential.getString(CredentialsConstants.FIELD_TYPE))) {
                    if (clientContext != null) {
                        final AtomicBoolean match = new AtomicBoolean(true);
                        clientContext.forEach(field -> {
                            if (authIdCredential.containsKey(field.getKey())) {
                                if (!authIdCredential.getString(field.getKey()).equals(field.getValue())) {
                                    match.set(false);
                                }
                            } else {
                                match.set(false);
                            }
                        });
                        if (!match.get()) {
                            continue;
                        }
                    }
                    return authIdCredential;
                }
            }
        }
    }
    return null;
}