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:org.apache.hadoop.hbase.client.SpeculativeMutater.java

public Boolean mutate(final long waitToSendFailover, final long waitToSendFailoverWithException,
        final HBaseTableFunction<Void> function, final HTableInterface primaryTable,
        final Collection<HTableInterface> failoverTables, final AtomicLong lastPrimaryFail,
        final int waitTimeFromLastPrimaryFail) {
    ExecutorCompletionService<Boolean> exeS = new ExecutorCompletionService<Boolean>(exe);

    ArrayList<Callable<Boolean>> callables = new ArrayList<Callable<Boolean>>();

    final AtomicBoolean isPrimarySuccess = new AtomicBoolean(false);
    final long startTime = System.currentTimeMillis();
    final long lastPrimaryFinalFail = lastPrimaryFail.get();

    if (System.currentTimeMillis() - lastPrimaryFinalFail > 5000) {
        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {
                try {
                    LOG.info(" --- CallingPrimary.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(primaryTable);
                    LOG.info(" --- CallingPrimary.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    isPrimarySuccess.set(true);
                    return true;
                } catch (java.io.InterruptedIOException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    lastPrimaryFail.set(System.currentTimeMillis());
                    Thread.currentThread().interrupt();
                }/*  www .  j  a  v a2  s  .com*/
                return null;
            }
        });
    }

    for (final HTableInterface failoverTable : failoverTables) {
        callables.add(new Callable<Boolean>() {

            public Boolean call() throws Exception {
                long waitToRequest = (System.currentTimeMillis() - lastPrimaryFinalFail > 5000)
                        ? waitToSendFailover - (System.currentTimeMillis() - startTime)
                        : waitToSendFailoverWithException - (System.currentTimeMillis() - startTime);

                LOG.info(" --- waitToRequest:" + waitToRequest + ","
                        + (System.currentTimeMillis() - lastPrimaryFinalFail) + ","
                        + (waitToSendFailover - (System.currentTimeMillis() - startTime)) + ","
                        + (waitToSendFailoverWithException - (System.currentTimeMillis() - startTime)));

                if (waitToRequest > 0) {
                    Thread.sleep(waitToRequest);
                }
                LOG.info(" --- isPrimarySuccess.get():" + isPrimarySuccess.get());
                if (isPrimarySuccess.get() == false) {
                    LOG.info(" --- CallingFailOver.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(failoverTable);
                    LOG.info(" --- CallingFailOver.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                }

                return false;
            }
        });
    }
    try {

        for (Callable<Boolean> call : callables) {
            exeS.submit(call);
        }
        Boolean result = exeS.take().get();
        return result;
    } catch (InterruptedException e) {
        e.printStackTrace();
        LOG.error(e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        LOG.error(e);
    }
    return null;
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions.java

@Override
public boolean enableOnly(Principal principal, Set<Action> actions) {
    final AtomicBoolean result = new AtomicBoolean(false);

    getAvailableActions().stream().forEach(available -> {
        available.stream().forEach(child -> {
            if (actions.contains(child)) {
                result.set(togglePermission(child, principal, true) || result.get());
            } else {
                togglePermission(child, principal, false);
            }/*  www .  ja  v  a2 s .  com*/
        });
    });

    return result.get();
}

From source file:com.jivesoftware.os.amza.service.storage.binary.BinaryRowReaderWriterTest.java

@Test(enabled = false)
public void testConcurrency() throws Exception {
    MemoryBackedWALFiler walFiler = new MemoryBackedWALFiler(
            new MultiAutoGrowingByteBufferBackedFiler(32, 1_024 * 1_024, new HeapByteBufferFactory()));
    IoStats ioStats = new IoStats();
    BinaryRowReader binaryRowReader = new BinaryRowReader(walFiler);
    BinaryRowWriter binaryRowWriter = new BinaryRowWriter(walFiler);

    ExecutorService executors = Executors.newFixedThreadPool(9);
    AtomicBoolean running = new AtomicBoolean(true);
    AtomicLong scanned = new AtomicLong();
    List<Future<?>> futures = Lists.newArrayList();
    for (int i = 0; i < 8; i++) {
        futures.add(executors.submit(() -> {
            try {
                while (running.get()) {
                    binaryRowReader.scan(ioStats, 0, false, (rowFP, rowTxId, rowType, row) -> {
                        scanned.incrementAndGet();
                        return true;
                    });/*from  w w w.  ja v  a  2  s . com*/
                }
                return true;
            } catch (Throwable t) {
                t.printStackTrace();
                throw t;
            }
        }));
    }
    futures.add(executors.submit(() -> {
        try {
            for (int i = 0; i < 1_000_000; i++) {
                byte[] row = UIO.intBytes(i);
                binaryRowWriter.write(ioStats, i, RowType.primary, 1, 16, stream -> stream.stream(row),
                        stream -> true,
                        (txId, prefix, key, value, valueTimestamp, valueTombstoned, valueVersion, fp) -> true,
                        false, false);
                if (i % 10_000 == 0) {
                    System.out.println("Finished i:" + i + " scanned:" + scanned.get());
                }
            }
        } finally {
            running.set(false);
        }
        return null;
    }));

    for (Future<?> future : futures) {
        future.get();
    }
}

From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java

@Test
public void testThatNamedPipeThrows() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String FIFO_NAME = "bFifo";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*from w  w  w. j  a  v a2s  .  c o m*/
        Runtime.getRuntime().exec("mkfifo " + Paths.get(tempDirectory.toString(), FIFO_NAME)).waitFor();
        new FileObjectGetter(tempDirectory).buildChannel(FIFO_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(FIFO_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertTrue(caughtException.get());
}

From source file:ca.rmen.android.networkmonitor.app.dialog.ChoiceDialogFragment.java

/**
 * @return a Dialog with a list of items, one of them possibly pre-selected.
 *///  w w  w.j a v  a 2 s.com
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Log.v(TAG, "onCreateDialog: savedInstanceState = " + savedInstanceState);
    Context context = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    Bundle arguments = getArguments();
    builder.setTitle(arguments.getString(DialogFragmentFactory.EXTRA_TITLE));
    final int actionId = arguments.getInt(DialogFragmentFactory.EXTRA_ACTION_ID);
    int selectedItem = arguments.getInt(DialogFragmentFactory.EXTRA_SELECTED_ITEM);
    final CharSequence[] choices = arguments.getCharSequenceArray(DialogFragmentFactory.EXTRA_CHOICES);
    OnClickListener listener = null;
    final AtomicBoolean hasClicked = new AtomicBoolean(false);
    if (getActivity() instanceof DialogItemListener) {
        listener = new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FragmentActivity activity = getActivity();
                if (activity == null) {
                    Log.w(TAG, "User clicked on dialog after it was detached from activity. Monkey?");
                } else if (hasClicked.get()) {
                    Log.w(TAG, "User already clicked once on this dialog! Monkey?");
                } else {
                    hasClicked.set(true);
                    ((DialogItemListener) activity).onItemSelected(actionId, choices, which);
                }
            }
        };
    }
    // If one item is to be pre-selected, use the single choice items layout.
    if (selectedItem >= 0)
        builder.setSingleChoiceItems(choices, selectedItem, listener);
    // If no particular item is to be pre-selected, use the default list item layout.
    else
        builder.setItems(choices, listener);

    if (getActivity() instanceof OnCancelListener)
        builder.setOnCancelListener((OnCancelListener) getActivity());
    final Dialog dialog = builder.create();
    if (getActivity() instanceof OnDismissListener)
        dialog.setOnDismissListener((OnDismissListener) getActivity());
    return dialog;
}

From source file:org.apache.samza.coordinator.AzureJobCoordinator.java

/**
 * Creates a listener for LeaderBarrierCompleteScheduler class.
 * Invoked by the leader when it detects that rebalancing has completed by polling the processor table.
 * Updates the barrier state on the blob to denote that the barrier has completed.
 * Cancels all future tasks scheduled by the LeaderBarrierComplete scheduler to check if barrier has completed.
 * @return an instance of SchedulerStateChangeListener.
 *//*  w w  w.ja  v a  2s  .c o  m*/
private SchedulerStateChangeListener createLeaderBarrierCompleteListener(String nextJMVersion,
        AtomicBoolean barrierTimeout) {
    return () -> {
        versionUpgradeDetected.getAndSet(false);
        String state;
        if (barrierTimeout.get()) {
            LOG.error("Barrier timed out for version {}", nextJMVersion);
            state = BarrierState.TIMEOUT.name() + " " + nextJMVersion;
        } else {
            LOG.info("Leader detected barrier completion.");
            state = BarrierState.END.name() + " " + nextJMVersion;
        }
        if (!leaderBlob.publishBarrierState(state, azureLeaderElector.getLeaseId().get())) {
            LOG.info("Leader failed to publish the job model {}. Stopping the processor with PID: .", jobModel,
                    processorId);
            stop();
            table.deleteProcessorEntity(currentJMVersion.get(), processorId);
        }
        leaderBarrierScheduler.shutdown();
    };
}

From source file:org.apache.hadoop.hbase.regionserver.TestRegionReplicaFailover.java

/**
 * Tests the case where there are 3 region replicas and the primary is continuously accepting
 * new writes while one of the secondaries is killed. Verification is done for both of the
 * secondary replicas./*from   ww  w.jav a 2 s. c o  m*/
 */
@Test(timeout = 120000)
public void testSecondaryRegionKillWhilePrimaryIsAcceptingWrites() throws Exception {
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
            Table table = connection.getTable(htd.getTableName());
            Admin admin = connection.getAdmin()) {
        // start a thread to do the loading of primary
        HTU.loadNumericRows(table, fam, 0, 1000); // start with some base
        admin.flush(table.getName());
        HTU.loadNumericRows(table, fam, 1000, 2000);

        final AtomicReference<Throwable> ex = new AtomicReference<Throwable>(null);
        final AtomicBoolean done = new AtomicBoolean(false);
        final AtomicInteger key = new AtomicInteger(2000);

        Thread loader = new Thread() {
            @Override
            public void run() {
                while (!done.get()) {
                    try {
                        HTU.loadNumericRows(table, fam, key.get(), key.get() + 1000);
                        key.addAndGet(1000);
                    } catch (Throwable e) {
                        ex.compareAndSet(null, e);
                    }
                }
            }
        };
        loader.start();

        Thread aborter = new Thread() {
            @Override
            public void run() {
                try {
                    boolean aborted = false;
                    for (RegionServerThread rs : HTU.getMiniHBaseCluster().getRegionServerThreads()) {
                        for (Region r : rs.getRegionServer().getOnlineRegions(htd.getTableName())) {
                            if (r.getRegionInfo().getReplicaId() == 1) {
                                LOG.info("Aborting region server hosting secondary region replica");
                                rs.getRegionServer().abort("for test");
                                aborted = true;
                            }
                        }
                    }
                    assertTrue(aborted);
                } catch (Throwable e) {
                    ex.compareAndSet(null, e);
                }
            };
        };

        aborter.start();
        aborter.join();
        done.set(true);
        loader.join();

        assertNull(ex.get());

        assertTrue(key.get() > 1000); // assert that the test is working as designed
        LOG.info("Loaded up to key :" + key.get());
        verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 0, 30000);
        verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 1, 30000);
        verifyNumericRowsWithTimeout(table, fam, 0, key.get(), 2, 30000);
    }

    // restart the region server
    HTU.getMiniHBaseCluster().startRegionServer();
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorTest.java

@Test
public void generateInternalPrimitiveTypeReturnsPrimitiveTypeWithoutGeneration()
        throws CodeGenerationException, IOException {
    JsonNode schemaNode = jsonNodeReader.fromReader(new StringReader("{\"type\": \"string\"}"));
    SchemaTree schema = schemaLoader.load(schemaNode);
    Mapping mapping = new Mapping(URI.create("http://example.com/type.json#"), ClassName.create(Integer.TYPE));
    final AtomicBoolean writeSourceCalled = new AtomicBoolean();
    PojoGenerator generator = new PojoGenerator(null, null, null) {
        @Override/* www  . j a va 2 s .c o  m*/
        protected void writeSource(URI type, ClassName className, Buffer buffer) throws IOException {
            writeSourceCalled.set(true);
        }
    };

    ClassName className = generator.generateInternal(mapping.getTarget(), schema, mapping);
    assertEquals(mapping.getClassName(), className);
    assertFalse(writeSourceCalled.get());
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorTest.java

@Test
public void generateInternalExistingTypeReturnsExistingTypeWithoutGeneration()
        throws CodeGenerationException, IOException {
    JsonNode schemaNode = jsonNodeReader.fromReader(new StringReader("{\"type\": \"string\"}"));
    SchemaTree schema = schemaLoader.load(schemaNode);
    Mapping mapping = new Mapping(URI.create("http://example.com/type.json#"),
            ClassName.create(TestClass.class));
    final AtomicBoolean writeSourceCalled = new AtomicBoolean();
    PojoGenerator generator = new PojoGenerator(null, null, null) {
        @Override//from w w  w  . j a  va  2 s .  c o  m
        protected void writeSource(URI type, ClassName className, Buffer buffer) throws IOException {
            writeSourceCalled.set(true);
        }
    };

    ClassName className = generator.generateInternal(mapping.getTarget(), schema, mapping);
    assertEquals(mapping.getClassName(), className);
    assertFalse(writeSourceCalled.get());
}