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:android.support.test.espresso.contrib.DrawerActions.java

/**
 * Returns true if the given matcher matches the drawer.
 *///from   ww w.  java 2 s. c o  m
private static boolean checkDrawer(int drawerLayoutId, final Matcher<View> matcher) {
    final AtomicBoolean matches = new AtomicBoolean(false);
    onView(withId(drawerLayoutId)).perform(new ViewAction() {

        @Override
        public Matcher<View> getConstraints() {
            return isAssignableFrom(DrawerLayout.class);
        }

        @Override
        public String getDescription() {
            return "check drawer";
        }

        @Override
        public void perform(UiController uiController, View view) {
            matches.set(matcher.matches(view));
        }
    });
    return matches.get();
}

From source file:com.clank.launcher.swing.SwingHelper.java

/**
 * Asks the user a binary yes or no question.
 *
 * @param parentComponent the component//  w  w  w .ja  v a2  s .c  o m
 * @param message the message to display
 * @param title the title string for the dialog
 * @return whether 'yes' was selected
 */
public static boolean confirmDialog(final Component parentComponent, @NonNull final String message,
        @NonNull final String title) {
    if (SwingUtilities.isEventDispatchThread()) {
        return JOptionPane.showConfirmDialog(parentComponent, message, title,
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    } else {
        // Use an AtomicBoolean to pass the result back from the
        // Event Dispatcher Thread
        final AtomicBoolean yesSelected = new AtomicBoolean();

        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    yesSelected.set(confirmDialog(parentComponent, title, message));
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return yesSelected.get();
    }
}

From source file:dk.netarkivet.common.utils.ProcessUtils.java

/** Wait for the end of a process, but only for a limited time.  This
 * method takes care of the ways waitFor can get interrupted.
 *
 * @param p Process to wait for//from   ww  w . jav a 2s.  co m
 * @param maxWait The maximum number of milliseconds to wait for the
 * process to exit.
 * @return Exit value for process, or null if the process didn't exit
 * within the expected time.
 */
public static Integer waitFor(final Process p, long maxWait) {
    ArgumentNotValid.checkNotNull(p, "Process p");
    ArgumentNotValid.checkPositive(maxWait, "long maxWait");
    long startTime = System.currentTimeMillis();
    Timer timer = new Timer(true);
    final Thread waitThread = Thread.currentThread();
    boolean wakeupScheduled = false;
    final AtomicBoolean doneWaiting = new AtomicBoolean(false);
    while (System.currentTimeMillis() < startTime + maxWait) {
        try {
            if (!wakeupScheduled) {
                // First time in here, we need to start the wakup thread,
                // but be sure it doesn't notify us too early or too late.
                synchronized (waitThread) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            synchronized (waitThread) {
                                if (!doneWaiting.get()) {
                                    waitThread.interrupt();
                                }
                            }
                        }
                    }, maxWait);
                    wakeupScheduled = true;
                }
            }

            p.waitFor();
            break;
        } catch (InterruptedException e) {
            // May happen for a number of reasons.  We just check if we've
            // timed out yet when we go through the loop again.
        }
    }
    synchronized (waitThread) {
        timer.cancel();
        doneWaiting.set(true);
        Thread.interrupted(); // In case the timer task interrupted.
    }
    try {
        return p.exitValue();
    } catch (IllegalThreadStateException e) {
        log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime)
                + " milliseconds");
        return null;
    }
}

From source file:org.apache.accumulo.test.functional.FunctionalTestUtils.java

public static void createRFiles(final AccumuloClient c, final FileSystem fs, String path, int rows, int splits,
        int threads) throws Exception {
    fs.delete(new Path(path), true);
    ExecutorService threadPool = Executors.newFixedThreadPool(threads);
    final AtomicBoolean fail = new AtomicBoolean(false);
    for (int i = 0; i < rows; i += rows / splits) {
        TestIngest.IngestParams params = new TestIngest.IngestParams(c.properties());
        params.outputFile = String.format("%s/mf%s", path, i);
        params.random = 56;/*from  w ww.  jav a 2s  .  c  o m*/
        params.timestamp = 1;
        params.dataSize = 50;
        params.rows = rows / splits;
        params.startRow = i;
        params.cols = 1;
        threadPool.execute(() -> {
            try {
                TestIngest.ingest(c, fs, params);
            } catch (Exception e) {
                fail.set(true);
            }
        });
    }
    threadPool.shutdown();
    threadPool.awaitTermination(1, TimeUnit.HOURS);
    assertFalse(fail.get());
}

From source file:io.cloudslang.engine.queue.services.recovery.ExecutionRecoveryServiceImpl.java

protected void assignRecoveredMessages() {
    if (logger.isDebugEnabled())
        logger.debug("Reassigning recovered messages is being started");
    long time = System.currentTimeMillis();
    final AtomicBoolean shouldContinue = new AtomicBoolean(true);
    while (shouldContinue.get()) {
        List<ExecutionMessage> messages = executionQueueService.readMessagesByStatus(DEFAULT_POLL_SIZE,
                ExecStatus.RECOVERED);/*from   w  w w . j av a 2s  . c om*/
        messageRecoveryService.enqueueMessages(messages, ExecStatus.PENDING);
        shouldContinue.set(messages != null && messages.size() == DEFAULT_POLL_SIZE);
    }
    if (logger.isDebugEnabled())
        logger.debug(
                "Reassigning recovered messages is done in " + (System.currentTimeMillis() - time) + " ms");
}

From source file:org.apache.hadoop.hbase.client.TestAsyncGetMultiThread.java

private void run(AtomicBoolean stop) throws InterruptedException, ExecutionException {
    while (!stop.get()) {
        int i = ThreadLocalRandom.current().nextInt(COUNT);
        assertEquals(i, Bytes.toInt(CONN.getRawTable(TABLE_NAME)
                .get(new Get(Bytes.toBytes(String.format("%03d", i)))).get().getValue(FAMILY, QUALIFIER)));
    }//ww w.  ja v  a  2  s. c  o  m
}

From source file:io.cloudslang.engine.queue.services.recovery.WorkerRecoveryServiceImpl.java

@Override
@Transactional//from  ww w  . j a  va  2 s .  co  m
public void doWorkerRecovery(String workerUuid) {

    //lock this worker to synchronize with drain action
    workerLockService.lock(workerUuid);

    logger.warn("Worker [" + workerUuid + "] is going to be recovered");
    long time = System.currentTimeMillis();
    // change status to in_recovery in separate transaction in order to make it as quickly as possible
    // so keep-alive wont be stuck and assigning won't take this worker as candidate
    workerNodeService.updateStatusInSeparateTransaction(workerUuid, WorkerStatus.IN_RECOVERY);

    final AtomicBoolean shouldContinue = new AtomicBoolean(true);

    while (shouldContinue.get()) {
        shouldContinue.set(messageRecoveryService.recoverMessagesBulk(workerUuid, DEFAULT_POLL_SIZE));
    }

    String newWRV = UUID.randomUUID().toString();
    workerNodeService.updateWRV(workerUuid, newWRV);
    workerNodeService.updateStatus(workerUuid, WorkerStatus.RECOVERED);

    logger.warn(
            "Worker [" + workerUuid + "] recovery is done in " + (System.currentTimeMillis() - time) + " ms");
}

From source file:org.apache.hadoop.hbase.client.TestAsyncTableGetMultiThreaded.java

private void run(AtomicBoolean stop) throws InterruptedException, ExecutionException {
    while (!stop.get()) {
        for (int i = 0; i < COUNT; i++) {
            assertEquals(i, Bytes.toInt(TABLE.get(new Get(Bytes.toBytes(String.format("%03d", i)))).get()
                    .getValue(FAMILY, QUALIFIER)));
        }/*from  ww  w. j a v  a2s . c  o  m*/
    }
}

From source file:org.apache.bookkeeper.metadata.etcd.Etcd64bitIdGeneratorTest.java

/**
 * Test generating id in parallel and ensure there is no duplicated id.
 *//*from  w  ww.j  av a  2  s. co  m*/
@Test
public void testGenerateIdParallel() throws Exception {
    final int numThreads = 10;
    @Cleanup("shutdown")
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    final int numIds = 10000;
    final AtomicLong totalIds = new AtomicLong(numIds);
    final Set<Long> ids = Collections.newSetFromMap(new ConcurrentHashMap<>());
    final RateLimiter limiter = RateLimiter.create(1000);
    final CompletableFuture<Void> doneFuture = new CompletableFuture<>();
    for (int i = 0; i < numThreads; i++) {
        executor.submit(() -> {
            Client client = Client.builder().endpoints(etcdContainer.getClientEndpoint()).build();
            Etcd64bitIdGenerator gen = new Etcd64bitIdGenerator(client.getKVClient(), scope);

            AtomicBoolean running = new AtomicBoolean(true);

            while (running.get()) {
                limiter.acquire();

                GenericCallbackFuture<Long> genFuture = new GenericCallbackFuture<>();
                gen.generateLedgerId(genFuture);

                genFuture.thenAccept(lid -> {
                    boolean duplicatedFound = !(ids.add(lid));
                    if (duplicatedFound) {
                        running.set(false);
                        doneFuture.completeExceptionally(
                                new IllegalStateException("Duplicated id " + lid + " generated : " + ids));
                        return;
                    } else {
                        if (totalIds.decrementAndGet() <= 0) {
                            running.set(false);
                            doneFuture.complete(null);
                        }
                    }
                }).exceptionally(cause -> {
                    running.set(false);
                    doneFuture.completeExceptionally(cause);
                    return null;
                });
            }
        });
    }

    FutureUtils.result(doneFuture);
    assertTrue(totalIds.get() <= 0);
    assertTrue(ids.size() >= numIds);
}

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

protected T get(String name) throws IOException {
    File file = getFile(name);//from  w w  w  .j  a v a2 s  .  c  o  m
    rwl.readLock().lock();
    try {
        AtomicBoolean mustBeEvaluated = new AtomicBoolean(false);
        T item = getNoLock(file, name, mustBeEvaluated);
        if (!mustBeEvaluated.get())
            return item;
    } finally {
        rwl.readLock().unlock();
    }
    rwl.writeLock().lock();
    try {
        return getNoLock(file, name, null);
    } finally {
        rwl.writeLock().unlock();
    }
}