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.microsoft.tfs.core.clients.versioncontrol.engines.internal.CheckinEngine.java

/**
 * Uploads changes to the server for a checkin or shelve operation.
 * <p>//from ww w.  ja  v  a 2 s  . c  o  m
 * <!-- Event Origination Info -->
 * <p>
 * This method is an <b>core event origination point</b>. The
 * {@link EventSource} object that accompanies each event fired by this
 * method describes the execution context (current thread, etc.) when and
 * where this method was invoked.
 *
 * @param changes
 *        the changes to upload (must not be <code>null</code>)
 * @param forShelve
 *        if the upload is for a shelve, set to true so the correct event is
 *        raised, if for a normal checkin set to false.
 * @param saveUploadedContentAsBaselines
 *        if <code>true</code> the uploaded files are stored in the local
 *        workspace baseline folders, if <code>false</code> they are not.
 *        Pass <code>false</code> when calling for shelve (not check-in) and
 *        for check-in on server workspaces.
 * @throws CheckinException
 *         if conflicts caused the checkin to fail or if other errors
 *         occurred.
 * @throws CoreCancelException
 *         if the upload was cancelled by the user.
 */
public void uploadChanges(final PendingChange[] changes, final boolean forShelve,
        final boolean saveUploadedContentAsBaselines) throws CheckinException, CoreCancelException {
    Check.notNull(changes, "changes"); //$NON-NLS-1$

    /*
     * If this is a local workspace, and we are checking in (not shelving),
     * then the caller will have set the flag saveUploadedContentAsBaselines
     * to true. In that case we need to take a workspace lock over the
     * entire upload process, since we will be putting baselines into the
     * baseline folders during the upload process.
     */
    final WorkspaceLock workspaceLock = saveUploadedContentAsBaselines ? this.workspace.lock() : null;
    try {
        final TaskMonitor monitor = TaskMonitorService.getTaskMonitor();
        monitor.begin("", changes.length); //$NON-NLS-1$

        // We need to reconcile before uploading pending change content
        // because
        // the upload handler will reject uploads for items that don't have
        // pending change rows on the server.
        final AtomicBoolean pendingChangesUpdatedByServer = new AtomicBoolean();
        workspace.reconcile(false /* reconcileMissingLocalItems */, pendingChangesUpdatedByServer);

        // if the server updated pending changes behind our back, abort so
        // that
        // the user confirms that what they are checking in is correct.
        if (pendingChangesUpdatedByServer.get()) {
            throw new VersionControlException(Messages.getString("CheckinEngine.PendingChangesModified")); //$NON-NLS-1$
        }

        /*
         * Since we will dispatch some uploads to be completed in a
         * different thread (managed by an Executor), we have to keep track
         * of them here. The completion service wraps the bounded executor
         * shared by all GetEngines that use the same VersionControlClients.
         * The completion service only tracks the jobs we have submitted for
         * execution, so we can simply count the completed jobs to know when
         * they have all been processed.
         */
        final AccountingCompletionService<WorkerStatus> completions = new AccountingCompletionService<WorkerStatus>(
                client.getUploadDownloadWorkerExecutor());

        final AsyncCheckinOperation asyncOp = new AsyncCheckinOperation(workspaceLock);

        try {
            int uploadedCount = 0;

            for (final PendingChange change : changes) {
                throwIfCanceled(monitor);

                throwIfFatalError(asyncOp);

                final ChangeType changeType = change.getChangeType();

                final PendingChangeEvent event = new PendingChangeEvent(EventSource.newFromHere(), workspace,
                        change, OperationStatus.GETTING, ChangePendedFlags.UNKNOWN);

                if (forShelve) {
                    client.getEventEngine().fireBeforeShelvePendingChange(event);
                } else {
                    client.getEventEngine().fireBeforeCheckinPendingChange(event);
                }

                /*
                 * The edit flag will always be set for changes of type Add
                 * and Edit. During a merge, a delete flag and an edit flag
                 * may both exist on one item.
                 */

                if (changeType.contains(ChangeType.EDIT) && (changeType.contains(ChangeType.MERGE)
                        && changeType.contains(ChangeType.DELETE)) == false) {
                    // Upload the file.
                    monitor.setCurrentWorkDescription(
                            MessageFormat.format(Messages.getString("CheckinEngine.UploadingFormat"), //$NON-NLS-1$
                                    change.getServerItem()));

                    /*
                     * In a strange circumstance in which a user pends a
                     * change on a file, changes his workspace so that the
                     * directory for that file points to somewhere else in
                     * the repository, then pends an add on the same file,
                     * the server loses the local item location of a pending
                     * change this can also happen if the user has made
                     * incorrect calls to update local version
                     */
                    if (change.getLocalItem() == null) {
                        throw new VersionControlException(MessageFormat.format(
                                Messages.getString("CheckinEngine.NoLocalFileForPendingChangeFormat"), //$NON-NLS-1$
                                change.getServerItem()));
                    }

                    /*
                     * In a local workspace, uploading changes is a
                     * yieldable operation. Check every N pending changes
                     * for a waiter and yield.
                     */
                    if (null != asyncOp.getBaselineFolders() && 0 == (uploadedCount++ % UPLOAD_YIELD_COUNT)) {
                        asyncOp.getWorkspaceLock().yield();
                    }

                    uploadFile(change, completions, asyncOp);
                } else if (changeType.contains(ChangeType.DELETE) == false
                        && changeType.contains(ChangeType.LOCK) == false
                        && changeType.contains(ChangeType.RENAME) == false
                        && changeType.contains(ChangeType.UNDELETE) == false
                        && changeType.contains(ChangeType.BRANCH) == false
                        && changeType.contains(ChangeType.ENCODING) == false
                        && changeType.contains(ChangeType.MERGE) == false) {
                }

                monitor.worked(1);
            }
        } finally {
            /*
             * Wait for all the background threads to finish.
             */
            waitForCompletions(completions);

            monitor.done();
        }

        throwIfCanceled(monitor);

        throwIfFatalError(asyncOp);
    } finally {
        if (workspaceLock != null) {
            workspaceLock.close();
        }
    }
}

From source file:org.apache.hadoop.hbase.procedure2.TestProcedureSuspended.java

@Test(timeout = 10000)
public void testSuspendWhileHoldingLocks() {
    final AtomicBoolean lockA = new AtomicBoolean(false);
    final AtomicBoolean lockB = new AtomicBoolean(false);

    final TestLockProcedure p1keyA = new TestLockProcedure(lockA, "keyA", false, true);
    final TestLockProcedure p2keyA = new TestLockProcedure(lockA, "keyA", false, true);
    final TestLockProcedure p3keyB = new TestLockProcedure(lockB, "keyB", false, true);

    procExecutor.submitProcedure(p1keyA);
    procExecutor.submitProcedure(p2keyA);
    procExecutor.submitProcedure(p3keyB);

    // first run p1, p3 are able to run p2 is blocked by p1
    waitAndAssertTimestamp(p1keyA, 1, 1);
    waitAndAssertTimestamp(p2keyA, 0, -1);
    waitAndAssertTimestamp(p3keyB, 1, 2);
    assertEquals(true, lockA.get());
    assertEquals(true, lockB.get());/*from ww  w.ja v a2s  .c  o m*/

    // release p3
    p3keyB.setThrowSuspend(false);
    procExecutor.getScheduler().addFront(p3keyB);
    waitAndAssertTimestamp(p1keyA, 1, 1);
    waitAndAssertTimestamp(p2keyA, 0, -1);
    waitAndAssertTimestamp(p3keyB, 2, 3);
    assertEquals(true, lockA.get());

    // wait until p3 is fully completed
    ProcedureTestingUtility.waitProcedure(procExecutor, p3keyB);
    assertEquals(false, lockB.get());

    // rollback p2 and wait until is fully completed
    p1keyA.setTriggerRollback(true);
    procExecutor.getScheduler().addFront(p1keyA);
    ProcedureTestingUtility.waitProcedure(procExecutor, p1keyA);

    // p2 should start and suspend
    waitAndAssertTimestamp(p1keyA, 4, 60000);
    waitAndAssertTimestamp(p2keyA, 1, 7);
    waitAndAssertTimestamp(p3keyB, 2, 3);
    assertEquals(true, lockA.get());

    // wait until p2 is fully completed
    p2keyA.setThrowSuspend(false);
    procExecutor.getScheduler().addFront(p2keyA);
    ProcedureTestingUtility.waitProcedure(procExecutor, p2keyA);
    waitAndAssertTimestamp(p1keyA, 4, 60000);
    waitAndAssertTimestamp(p2keyA, 2, 8);
    waitAndAssertTimestamp(p3keyB, 2, 3);
    assertEquals(false, lockA.get());
    assertEquals(false, lockB.get());
}

From source file:com.nesscomputing.jackson.datatype.TestCustomUuidModule.java

@Test
public void testCustomUUIDDeserialization() throws Exception {
    final UUID orig = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
    final AtomicBoolean called = new AtomicBoolean(false);
    ObjectMapper mapper = getObjectMapper(new AbstractModule() {
        @Override// w  w  w .  j  av  a  2s .  co  m
        protected void configure() {
            bind(new TypeLiteral<JsonDeserializer<UUID>>() {
            }).toInstance(new CustomUuidDeserializer() {
                private static final long serialVersionUID = 1L;

                @Override
                protected UUID _deserialize(String value, DeserializationContext ctxt)
                        throws IOException, JsonProcessingException {
                    UUID foo = super._deserialize(value, ctxt);
                    called.set(true);
                    return foo;
                }
            });
        }
    });
    UUID uuid = mapper.readValue('"' + orig.toString() + '"', new TypeReference<UUID>() {
    });
    Assert.assertEquals(orig, uuid);
    Assert.assertTrue(called.get());
}

From source file:com.datatorrent.stram.StramRecoveryTest.java

@Test
public void testRpcFailover() throws Exception {
    String appPath = testMeta.getPath();
    Configuration conf = new Configuration(false);
    final AtomicBoolean timedout = new AtomicBoolean();

    StreamingContainerUmbilicalProtocol impl = MockitoUtil
            .mockProtocol(StreamingContainerUmbilicalProtocol.class);

    Mockito.doAnswer(new org.mockito.stubbing.Answer<Void>() {
        @Override//from   w w w  .  j av a2 s .com
        public Void answer(InvocationOnMock invocation) {
            LOG.debug("got call: " + invocation.getMethod());
            if (!timedout.get()) {
                try {
                    timedout.set(true);
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                //throw new RuntimeException("fail");
            }
            return null;
        }
    }).when(impl).log("containerId", "timeout");

    Server server = new RPC.Builder(conf).setProtocol(StreamingContainerUmbilicalProtocol.class)
            .setInstance(impl).setBindAddress("0.0.0.0").setPort(0).setNumHandlers(1).setVerbose(false).build();
    server.start();
    InetSocketAddress address = NetUtils.getConnectAddress(server);
    LOG.info("Mock server listening at " + address);

    int rpcTimeoutMillis = 500;
    int retryDelayMillis = 100;
    int retryTimeoutMillis = 500;

    FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(appPath, conf);
    URI uri = RecoverableRpcProxy.toConnectURI(address, rpcTimeoutMillis, retryDelayMillis, retryTimeoutMillis);
    recoveryHandler.writeConnectUri(uri.toString());

    RecoverableRpcProxy rp = new RecoverableRpcProxy(appPath, conf);
    StreamingContainerUmbilicalProtocol protocolProxy = rp.getProxy();
    protocolProxy.log("containerId", "msg");
    // simulate socket read timeout
    try {
        protocolProxy.log("containerId", "timeout");
        Assert.fail("expected socket timeout");
    } catch (java.net.SocketTimeoutException e) {
        // expected
    }
    Assert.assertTrue("timedout", timedout.get());
    rp.close();

    // test success on retry
    timedout.set(false);
    retryTimeoutMillis = 1500;
    uri = RecoverableRpcProxy.toConnectURI(address, rpcTimeoutMillis, retryDelayMillis, retryTimeoutMillis);
    recoveryHandler.writeConnectUri(uri.toString());

    protocolProxy.log("containerId", "timeout");
    Assert.assertTrue("timedout", timedout.get());

    rp.close();

    String rpcTimeout = System.getProperty(RecoverableRpcProxy.RPC_TIMEOUT);
    String rpcRetryDelay = System.getProperty(RecoverableRpcProxy.RETRY_DELAY);
    String rpcRetryTimeout = System.getProperty(RecoverableRpcProxy.RETRY_TIMEOUT);

    System.setProperty(RecoverableRpcProxy.RPC_TIMEOUT, Integer.toString(500));
    System.setProperty(RecoverableRpcProxy.RETRY_DELAY, Long.toString(100));
    System.setProperty(RecoverableRpcProxy.RETRY_TIMEOUT, Long.toString(500));

    timedout.set(false);
    uri = RecoverableRpcProxy.toConnectURI(address);
    recoveryHandler.writeConnectUri(uri.toString());

    rp = new RecoverableRpcProxy(appPath, conf);
    protocolProxy = rp.getProxy();
    protocolProxy.log("containerId", "msg");
    try {
        protocolProxy.log("containerId", "timeout");
        Assert.fail("expected socket timeout");
    } catch (java.net.SocketTimeoutException e) {
        // expected
    }
    Assert.assertTrue("timedout", timedout.get());
    rp.close();

    timedout.set(false);
    System.setProperty(RecoverableRpcProxy.RETRY_TIMEOUT, Long.toString(1500));

    uri = RecoverableRpcProxy.toConnectURI(address);
    recoveryHandler.writeConnectUri(uri.toString());

    protocolProxy.log("containerId", "timeout");
    Assert.assertTrue("timedout", timedout.get());

    restoreSystemProperty(RecoverableRpcProxy.RPC_TIMEOUT, rpcTimeout);
    restoreSystemProperty(RecoverableRpcProxy.RETRY_DELAY, rpcRetryDelay);
    restoreSystemProperty(RecoverableRpcProxy.RETRY_TIMEOUT, rpcRetryTimeout);

    server.stop();
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.providers.aws.AmazonImageTagger.java

/**
 * Return true iff the tags on the current machine image match the desired.
 *///  ww  w  .  java 2  s.  c  o m
@Override
public boolean areImagesTagged(Collection<Image> targetImages, Stage stage) {
    Collection<MatchedImage> matchedImages = findImages(
            targetImages.stream().map(targetImage -> targetImage.imageName).collect(Collectors.toList()),
            stage);

    AtomicBoolean isUpserted = new AtomicBoolean(true);
    for (Image targetImage : targetImages) {
        targetImage.regions.forEach(region -> {
            MatchedImage matchedImage = matchedImages.stream()
                    .filter(m -> m.imageName.equals(targetImage.imageName)).findFirst().orElse(null);

            if (matchedImage == null) {
                isUpserted.set(false);
                return;
            }

            List<String> imagesForRegion = matchedImage.amis.get(region);
            imagesForRegion.forEach(image -> {
                Map<String, String> allImageTags = matchedImage.tagsByImageId.get(image);
                targetImage.tags.entrySet().forEach(entry -> {
                    // assert tag equality
                    isUpserted
                            .set(isUpserted.get() && entry.getValue().equals(allImageTags.get(entry.getKey())));
                });
            });
        });
    }

    return isUpserted.get();
}

From source file:org.zodiark.service.publisher.PublisherServiceImpl.java

private boolean validateSubscriberState(String subscriberId, final PublisherEndpoint p) {
    final AtomicBoolean isValid = new AtomicBoolean();
    // DAangerous if the path change.
    eventBus.message(RETRIEVE_SUBSCRIBER, subscriberId, new Reply<SubscriberEndpoint, String>() {
        @Override// ww  w  .j av a 2 s. c o  m
        public void ok(SubscriberEndpoint s) {
            isValid.set(s.publisherEndpoint().equals(p));
        }

        @Override
        public void fail(ReplyException replyException) {
            logger.error("No Endpoint");
        }
    });
    return isValid.get();
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;/*from ww  w.  j av  a 2  s. c om*/
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.workers.GetDownloadWorker.java

/**
 * {@inheritDoc}/*from w  w w.  ja  v a 2s.c o m*/
 */
@Override
public WorkerStatus call() throws Exception {
    /*
     * Try not to run any code outside this try block, so our Throwable
     * catch below can report every error (even RuntimeExceptions).
     */
    try {
        if (getCancelMonitor().isCanceled()) {
            return new WorkerStatus(this, FinalState.CANCELED);
        }

        final AtomicBoolean targetSymLink = new AtomicBoolean();
        final AtomicBoolean targetSymLinkDestinationUnmapped = new AtomicBoolean();

        // Get the target file, updating local workspace baselines if
        // appropriate.
        downloadFile(targetSymLink, targetSymLinkDestinationUnmapped);

        // Sends version updates to the server, sets attributes
        completeGetOperation(targetSymLink.get(), targetSymLinkDestinationUnmapped.get());
    } catch (final VersionControlException e) {
        // Convert to a non-fatal (this handles IOExceptions wrapped as
        // VersionControlExceptions)

        log.warn("Converted to non-fatal", e); //$NON-NLS-1$

        getEngine.onNonFatalError(
                new VersionControlException(
                        MessageFormat.format(Messages.getString("GetEngineDownloadWorker.AColonBFormat"), //$NON-NLS-1$
                                operation.getTargetLocalItem(), e.getLocalizedMessage()),
                        e),
                asyncOp.getWorkspace());
    } catch (final CanceledException e) {
        /*
         * CoreCancelException is thrown if the user cancels during the
         * download or completion. There's no cleanup to do because all
         * temporary resources were cleaned up as the exception travelled
         * through the stack.
         */
        return new WorkerStatus(this, FinalState.CANCELED);
    } catch (final Throwable t) {
        /*
         * An unexpected (fatal) error happened. We have to communicate this
         * problem to the thread submitting tasks so it can take the correct
         * action (shut down other workers).
         *
         * VS checks for certain kinds of fatal vs. non-fatal exceptions
         * here, but we'll just consider them all fatal for now.
         */
        asyncOp.setFatalError(t);
        return new WorkerStatus(this, FinalState.ERROR);
    }

    return new WorkerStatus(this, FinalState.NORMAL);
}

From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java

@Test
public void testBasicHystrixCommand() throws Exception {

    final AtomicBoolean done = new AtomicBoolean(false);
    final AtomicReference<String> result = new AtomicReference<>(null);

    // kick off async command
    Observable<String> observable = new TestCommand().observe();

    // Sleep to test what happens if command finishes before subscription
    Thread.sleep(2000);// ww w .j  a v a 2  s.  c o m

    // Add handler
    observable.subscribe(new Observer<String>() {
        @Override
        public void onCompleted() {
            done.set(true);
        }

        @Override
        public void onError(Throwable e) {
            result.set("error!!");
            done.set(true);
        }

        @Override
        public void onNext(String args) {
            result.set(args);
            done.set(true);
        }
    });

    // spin until done
    while (!done.get()) {
        Thread.sleep(100);
    }

    Assert.assertEquals(resultString, result.get());
}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing non-emulated command.
 *///w  ww  .ja v  a2 s  . c om
@Test
public void executeCommand_delegate() {
    Assume.assumeTrue("not unix-like", SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_LINUX);

    File touch = new File("/usr/bin/touch");
    Assume.assumeTrue("no 'touch' command", touch.isFile() && touch.canExecute());

    AtomicBoolean call = new AtomicBoolean();
    MockCommandEmulator.callback(args -> call.set(true));
    File target = new File(framework.getWork("working"), "target");
    Assume.assumeFalse(target.exists());

    // exec: touch .../target
    TestExecutionPlan.Command command = command("generic", touch.getPath(), target.getAbsolutePath());
    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(command, Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(target.exists(), is(true));
    assertThat(call.get(), is(false));
}