Example usage for java.util.concurrent.atomic AtomicInteger decrementAndGet

List of usage examples for java.util.concurrent.atomic AtomicInteger decrementAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger decrementAndGet.

Prototype

public final int decrementAndGet() 

Source Link

Document

Atomically decrements the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:com.indeed.lsmtree.core.TestStore.java

public void testStore(StorageType storageType, CompressionCodec codec) throws Exception {
    File indexDir = new File(tmpDir, "index");
    indexDir.mkdirs();//www.j  a  v a 2s .  c om
    File indexLink = new File(tmpDir, "indexlink");
    PosixFileOperations.link(indexDir, indexLink);
    File storeDir = new File(indexLink, "store");
    Store<Integer, Long> store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(),
            new LongSerializer()).setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType)
                    .setCodec(codec).build();
    final Random r = new Random(0);
    final int[] ints = new int[treeSize];
    for (int i = 0; i < ints.length; i++) {
        ints[i] = r.nextInt();
    }
    for (final int i : ints) {
        store.put(i, (long) i);
        assertTrue(store.get(i) == i);
    }
    for (final int i : ints) {
        assertTrue(store.get(i) == i);
    }
    store.close();
    store.waitForCompactions();
    store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer())
            .setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType).setCodec(codec).build();
    Arrays.sort(ints);
    Iterator<Store.Entry<Integer, Long>> iterator = store.iterator();
    int index = 0;
    while (iterator.hasNext()) {
        Store.Entry<Integer, Long> next = iterator.next();
        int current = ints[index];
        assertTrue(next.getKey() == ints[index]);
        assertTrue(next.getValue() == ints[index]);
        while (index < ints.length && ints[index] == current) {
            index++;
        }
    }
    assertTrue(index == ints.length);
    final BitSet deleted = new BitSet();
    for (int i = 0; i < ints.length / 10; i++) {
        int deletionIndex = r.nextInt(ints.length);
        deleted.set(deletionIndex, true);
        for (int j = deletionIndex - 1; j >= 0; j--) {
            if (ints[j] == ints[deletionIndex]) {
                deleted.set(j, true);
            } else {
                break;
            }
        }
        for (int j = deletionIndex + 1; j < ints.length; j++) {
            if (ints[j] == ints[deletionIndex]) {
                deleted.set(j, true);
            } else {
                break;
            }
        }
        store.delete(ints[deletionIndex]);
        assertNull(store.get(ints[deletionIndex]));
    }
    iterator = store.iterator();
    index = 0;
    while (iterator.hasNext()) {
        Store.Entry<Integer, Long> next = iterator.next();
        while (deleted.get(index))
            index++;
        int current = ints[index];
        assertTrue(next.getKey() == ints[index]);
        assertTrue(next.getValue() == ints[index]);
        while (index < ints.length && ints[index] == current) {
            index++;
        }
    }
    while (deleted.get(index))
        index++;
    assertTrue(index == ints.length);
    final int max = ints[ints.length - 1];
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < done.get(); i++) {
        final int thread = i;
        final Store<Integer, Long> finalStore = store;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Random r = new Random(thread);
                    for (int i = 0; i < treeSize; i++) {
                        int rand = r.nextInt();
                        int insertionindex = Arrays.binarySearch(ints, rand);

                        Store.Entry<Integer, Long> next = finalStore.ceil(rand);
                        boolean found = next != null;
                        if (insertionindex >= 0 && deleted.get(insertionindex)) {
                            assertNull(finalStore.get(ints[insertionindex]));
                        } else {
                            assertTrue(found == (rand <= max));
                            if (found) {
                                assertTrue(next.getKey() >= rand);
                                assertTrue(next.getKey().longValue() == next.getValue());
                                if (insertionindex >= 0) {
                                    assertTrue(rand == ints[insertionindex]);
                                    assertTrue(next.getKey() == rand);
                                    Long result = finalStore.get(rand);
                                    assertTrue(result == rand);
                                } else {
                                    int nextIndex = ~insertionindex;
                                    while (deleted.get(nextIndex) && nextIndex < ints.length)
                                        nextIndex++;
                                    if (nextIndex < ints.length) {
                                        if (insertionindex != -1)
                                            assertTrue(ints[(~insertionindex) - 1] < rand);
                                        assertTrue(ints[nextIndex] + " != " + next.getKey(),
                                                ints[nextIndex] == next.getKey());

                                    }
                                    Long result = finalStore.get(rand);
                                    assertTrue(result == null);
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    store.close();
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

private void createDiscoveredContainer(Consumer<Throwable> callback, AtomicInteger counter,
        ContainerState containerState) {
    logFine("Creating ContainerState for discovered container: %s", containerState.id);
    URI containerFactoryUri = UriUtils.buildUri(getHost(), ContainerFactoryService.class);
    sendRequest(OperationUtil.createForcedPost(containerFactoryUri).setBody(containerState)
            .setCompletion((o, ex) -> {
                if (ex != null) {
                    if (ex instanceof ServiceAlreadyStartedException) {
                        logWarning("Container state already exists for container (id=%s)", containerState.id);
                    } else {
                        logSevere("Failed to create ContainerState for discovered container (id=%s): %s",
                                containerState.id, ex.getMessage());
                        callback.accept(ex);
                        return;
                    }//w w w  . j  av a2s.  com
                } else {
                    logInfo("Created ContainerState for discovered container: %s", containerState.id);

                    // as soon as the ContainerService
                    // is started, its
                    // maintenance
                    // handler will be invoked to fetch
                    // up-to-date attributes
                }

                // Shouldn't create ContainerDescription
                // for system containers.
                String systemContainerName = matchSystemContainerName(
                        SystemContainerDescriptions.getSystemContainerNames(), containerState.names);

                if (systemContainerName == null) {
                    ContainerState body = o.getBody(ContainerState.class);
                    createDiscoveredContainerDescription(body);
                }

                if (counter.decrementAndGet() == 0) {
                    callback.accept(null);
                }
            }));
}

From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java

private ListenableFuture<Boolean> initializeDraftFromDatabase() {
    SettableFuture<Boolean> future = new SettableFuture<>();

    new AsyncTask<Void, Void, List<Draft>>() {
        @Override//from w  w w .ja va  2s . co  m
        protected List<Draft> doInBackground(Void... params) {
            DraftDatabase draftDatabase = DatabaseFactory.getDraftDatabase(ConversationActivity.this);
            List<Draft> results = draftDatabase.getDrafts(threadId);

            draftDatabase.clearDrafts(threadId);

            return results;
        }

        @Override
        protected void onPostExecute(List<Draft> drafts) {
            if (drafts.isEmpty()) {
                future.set(false);
                updateToggleButtonState();
                return;
            }

            AtomicInteger draftsRemaining = new AtomicInteger(drafts.size());
            AtomicBoolean success = new AtomicBoolean(false);
            ListenableFuture.Listener<Boolean> listener = new AssertedSuccessListener<Boolean>() {
                @Override
                public void onSuccess(Boolean result) {
                    success.compareAndSet(false, result);

                    if (draftsRemaining.decrementAndGet() <= 0) {
                        future.set(success.get());
                    }
                }
            };

            for (Draft draft : drafts) {
                try {
                    switch (draft.getType()) {
                    case Draft.TEXT:
                        composeText.setText(draft.getValue());
                        listener.onSuccess(true);
                        break;
                    case Draft.LOCATION:
                        attachmentManager.setLocation(SignalPlace.deserialize(draft.getValue()),
                                getCurrentMediaConstraints()).addListener(listener);
                        break;
                    case Draft.IMAGE:
                        setMedia(Uri.parse(draft.getValue()), MediaType.IMAGE).addListener(listener);
                        break;
                    case Draft.AUDIO:
                        setMedia(Uri.parse(draft.getValue()), MediaType.AUDIO).addListener(listener);
                        break;
                    case Draft.VIDEO:
                        setMedia(Uri.parse(draft.getValue()), MediaType.VIDEO).addListener(listener);
                        break;
                    case Draft.QUOTE:
                        SettableFuture<Boolean> quoteResult = new SettableFuture<>();
                        new QuoteRestorationTask(draft.getValue(), quoteResult).execute();
                        quoteResult.addListener(listener);
                        break;
                    }
                } catch (IOException e) {
                    Log.w(TAG, e);
                }
            }

            updateToggleButtonState();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    return future;
}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testLocking() throws Exception {

    if (Config.isHSQLDBUsed()) {
        LOG.warn("HDSQLDB doesnt seem to support SELECT FOR UPDATE properly so we don't test it any more");
        return;/*from  w  ww  .j a  va2s.  c om*/
    }

    final ProductManager productManager = ProductManager.getInstance();

    final Currency curr = C2LManager.getInstance().createCurrency("TestCurr");

    /** Verify that we can begin a transaction, lock an entity, then commit without an exception occurring. */
    {
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            final Product productForTest1 = productManager.createProduct("transactionLockingTest1");
            transaction.commit();
            transaction.begin();
            transaction.lock(productForTest1);
            transaction.commit();
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    {
        /** Verify that an IllegalStateException is thrown if we attempt to lock outside of a transaction. */
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            final Product productForTest2 = productManager.createProduct("transactionLockingTest2");
            transaction.lock(productForTest2);
            fail("Expected IllegalStateException to occur when attempting to lock an item outside of a transaction.");
        }
        // An IllegalStateException is expected for this test to pass.
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify that if we attempt to acquire a lock on the same entity multiple times from the same transaction, that
     * no errors occur.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            final Product productForTest3 = productManager.createProduct("transactionLockingTest3");
            transaction.begin();
            for (int i = 0; i < 10; i++) {
                transaction.lock(productForTest3);
            }
            transaction.commit();
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that if we begin a transaction, lock an entity, then commit multiple times that a lock can be acquired
     * each time.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest4 = productManager.createProduct("transactionLockingTest4");
            for (int i = 0; i < 10; i++) {
                assertNotNull("Transaction object is null", transaction);
                assertFalse("A previous transaction is already running.", transaction.isRunning());
                transaction.begin();
                transaction.lock(productForTest4);
                transaction.commit();
            }
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that if we begin a transaction, lock an entity, then rollback multiple times that a lock can be acquired
     * each time.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest5 = productManager.createProduct("transactionLockingTest5");
            for (int i = 0; i < 10; i++) {
                assertNotNull("Transaction object is null", transaction);
                assertFalse("A previous transaction is already running.", transaction.isRunning());
                transaction.begin();
                transaction.lock(productForTest5);
                transaction.rollback();
            }
        } catch (final Exception e) {
            transaction.rollback();
            throw e;
        }
    }

    /**
     * Verify that we can not lock after a transaction has been committed.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest6 = productManager.createProduct("transactionLockingTest6");
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            transaction.commit();
            transaction.lock(productForTest6);
            fail("A lock was acquired after the transaction has been committed.");
        }
        // An IllegalStateException is expected for the test to pass
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify that we can not lock after a transaction has been rolled back.
     */
    {
        final Transaction transaction = Transaction.current();
        try {
            final Product productForTest7 = productManager.createProduct("transactionLockingTest7");
            assertNotNull("Transaction object is null", transaction);
            assertFalse("A previous transaction is already running.", transaction.isRunning());
            transaction.begin();
            transaction.rollback();
            transaction.lock(productForTest7);
            fail("A lock was acquired after the transaction has been rolled back.");
        }
        // An IllegalStateException is expected for the test to pass
        catch (final IllegalStateException e) {
            //
        }
    }

    /**
     * Verify multiple threads attempting to lock the same object and the behavior that occurs.
     */
    try {
        final Order lockedOrder = OrderManager.getInstance().createOrder(//
                "lockedOrder", //
                JaloSession.getCurrentSession().getUser(), //
                curr, //
                Calendar.getInstance().getTime(), //
                true);
        lockedOrder.setTotal(0.0d);

        final ComposedType composedType = lockedOrder.getComposedType();

        final String checkQuery = "SELECT "
                + composedType.getAttributeDescriptorIncludingPrivate(Order.TOTAL).getDatabaseColumn()
                + " FROM " + composedType.getTable() + " WHERE PK = ?";

        final int THREADS = 16;

        // Create an executor service that uses 16 threads to test
        // the transaction locking
        final ExecutorService executor = Executors.newFixedThreadPool(//
                THREADS, //
                new ThreadFactory() {
                    final Tenant threadFactoryTenant = Registry.getCurrentTenant();

                    @Override
                    public Thread newThread(final Runnable runnable) {
                        return new Thread() {
                            protected void prepareThread() {
                                Registry.setCurrentTenant(threadFactoryTenant);
                            }

                            protected void unprepareThread() {
                                JaloSession.deactivate();
                                Registry.unsetCurrentTenant();
                            }

                            @Override
                            public void run() {
                                try {
                                    prepareThread();
                                    runnable.run();
                                } finally {
                                    unprepareThread();
                                }
                            }
                        };
                    }
                });

        // Create 8 callables that will concurrently
        // attempt to lock the same object.
        final AtomicInteger stackCounter = new AtomicInteger();
        final List<Callable<Object>> callables = new ArrayList<Callable<Object>>();
        for (int j = 0; j < THREADS; j++) {
            callables.add(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    final PK pk = lockedOrder.getPK();
                    if (pk == null) {
                        throw new IllegalStateException();
                    }

                    for (int k = 0; k < 100; k++) {
                        final Transaction transaction = Transaction.current();

                        assertNotNull("Transaction object is null", transaction);

                        PreparedStatement statement = null;
                        ResultSet resultSet = null;
                        try {
                            transaction.begin();
                            transaction.setTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
                            transaction.lock(lockedOrder);
                            final int stack = stackCounter.incrementAndGet();
                            if (stack > 1) {
                                stackCounter.decrementAndGet();
                                throw new IllegalStateException("Got " + stack + " threads in protected area!");
                            }

                            statement = transaction.getTXBoundConnection().prepareStatement(checkQuery);
                            statement.setLong(1, lockedOrder.getPK().getLongValue());
                            resultSet = statement.executeQuery();
                            if (!resultSet.next()) {
                                throw new IllegalStateException("Expected result set");
                            }
                            final double dbValue = resultSet.getDouble(1);
                            final double jaloValue = lockedOrder.getTotal();
                            if (Math.abs(dbValue - jaloValue) >= 1d) {
                                throw new IllegalStateException(
                                        "Jalo value differs from db value : " + jaloValue + "<>" + dbValue);
                            }

                            lockedOrder.setTotal(jaloValue + 1.0d);

                            stackCounter.decrementAndGet();
                            transaction.commit();
                        } catch (final Exception e) {
                            e.printStackTrace();
                            transaction.rollback();
                            throw e;
                        } finally {
                            Utilities.tryToCloseJDBC(null, statement, resultSet, true);
                        }
                    }
                    return null;
                }
            });
        }
        // Get the value of each future to determine if an exception was thrown.
        for (final Future<Object> future : executor.invokeAll(callables)) {
            future.get();
        }
        final double expected = THREADS * 100;
        assertEquals(//
                "Total value of order after all transaction differs", //
                expected, //
                ((Order) JaloSession.getCurrentSession().getItem(lockedOrder.getPK())).getTotal(), 0.000001);
    } catch (final IllegalStateException e) {
        e.printStackTrace();
        throw e;
    }

    /**
     * Verify changes to a value on a lock
     */

    // TODO:

    /**
     * Tests related to caching
     */

    // TODO:
}

From source file:com.twitter.distributedlog.BKLogHandler.java

private void asyncGetLedgerListInternal(final Comparator<LogSegmentMetadata> comparator,
        final LogSegmentFilter segmentFilter, final Watcher watcher,
        final GenericCallback<List<LogSegmentMetadata>> finalCallback, final AtomicInteger numAttemptsLeft,
        final AtomicLong backoffMillis) {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {//from  w  w  w  .  j a  va2s  .  co m
        if (LOG.isTraceEnabled()) {
            LOG.trace("Async getting ledger list for {}.", getFullyQualifiedName());
        }
        final GenericCallback<List<LogSegmentMetadata>> callback = new GenericCallback<List<LogSegmentMetadata>>() {
            @Override
            public void operationComplete(int rc, List<LogSegmentMetadata> result) {
                long elapsedMicros = stopwatch.stop().elapsed(TimeUnit.MICROSECONDS);
                if (KeeperException.Code.OK.intValue() != rc) {
                    getListStat.registerFailedEvent(elapsedMicros);
                } else {
                    if (LogSegmentFilter.DEFAULT_FILTER == segmentFilter) {
                        isFullListFetched.set(true);
                    }
                    getListStat.registerSuccessfulEvent(elapsedMicros);
                }
                finalCallback.operationComplete(rc, result);
            }
        };
        zooKeeperClient.get().getChildren(logMetadata.getLogSegmentsPath(), watcher,
                new AsyncCallback.Children2Callback() {
                    @Override
                    public void processResult(final int rc, final String path, final Object ctx,
                            final List<String> children, final Stat stat) {
                        if (KeeperException.Code.OK.intValue() != rc) {

                            if ((KeeperException.Code.CONNECTIONLOSS.intValue() == rc
                                    || KeeperException.Code.SESSIONEXPIRED.intValue() == rc
                                    || KeeperException.Code.SESSIONMOVED.intValue() == rc)
                                    && numAttemptsLeft.decrementAndGet() > 0) {
                                long backoffMs = backoffMillis.get();
                                backoffMillis.set(Math.min(conf.getZKRetryBackoffMaxMillis(), 2 * backoffMs));
                                scheduler.schedule(new Runnable() {
                                    @Override
                                    public void run() {
                                        asyncGetLedgerListInternal(comparator, segmentFilter, watcher,
                                                finalCallback, numAttemptsLeft, backoffMillis);
                                    }
                                }, backoffMs, TimeUnit.MILLISECONDS);
                                return;
                            }
                            callback.operationComplete(rc, null);
                            return;
                        }

                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Got ledger list from {} : {}", logMetadata.getLogSegmentsPath(),
                                    children);
                        }

                        ledgerListWatchSet.set(true);
                        Set<String> segmentsReceived = new HashSet<String>();
                        segmentsReceived.addAll(segmentFilter.filter(children));
                        Set<String> segmentsAdded;
                        final Set<String> removedSegments = Collections.synchronizedSet(new HashSet<String>());
                        final Map<String, LogSegmentMetadata> addedSegments = Collections
                                .synchronizedMap(new HashMap<String, LogSegmentMetadata>());
                        Pair<Set<String>, Set<String>> segmentChanges = logSegmentCache.diff(segmentsReceived);
                        segmentsAdded = segmentChanges.getLeft();
                        removedSegments.addAll(segmentChanges.getRight());

                        if (segmentsAdded.isEmpty()) {
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("No segments added for {}.", getFullyQualifiedName());
                            }

                            // update the cache before fetch
                            logSegmentCache.update(removedSegments, addedSegments);

                            List<LogSegmentMetadata> segmentList;
                            try {
                                segmentList = getCachedLogSegments(comparator);
                            } catch (UnexpectedException e) {
                                callback.operationComplete(KeeperException.Code.DATAINCONSISTENCY.intValue(),
                                        null);
                                return;
                            }
                            callback.operationComplete(KeeperException.Code.OK.intValue(), segmentList);
                            notifyUpdatedLogSegments(segmentList);
                            if (!removedSegments.isEmpty()) {
                                notifyOnOperationComplete();
                            }
                            return;
                        }

                        final AtomicInteger numChildren = new AtomicInteger(segmentsAdded.size());
                        final AtomicInteger numFailures = new AtomicInteger(0);
                        for (final String segment : segmentsAdded) {
                            metadataStore.getLogSegment(logMetadata.getLogSegmentPath(segment))
                                    .addEventListener(new FutureEventListener<LogSegmentMetadata>() {

                                        @Override
                                        public void onSuccess(LogSegmentMetadata result) {
                                            addedSegments.put(segment, result);
                                            complete();
                                        }

                                        @Override
                                        public void onFailure(Throwable cause) {
                                            // NONODE exception is possible in two cases
                                            // 1. A log segment was deleted by truncation between the call to getChildren and read
                                            // attempt on the znode corresponding to the segment
                                            // 2. In progress segment has been completed => inprogress ZNode does not exist
                                            if (cause instanceof KeeperException
                                                    && KeeperException.Code.NONODE == ((KeeperException) cause)
                                                            .code()) {
                                                removedSegments.add(segment);
                                                complete();
                                            } else {
                                                // fail fast
                                                if (1 == numFailures.incrementAndGet()) {
                                                    int rcToReturn = KeeperException.Code.SYSTEMERROR
                                                            .intValue();
                                                    if (cause instanceof KeeperException) {
                                                        rcToReturn = ((KeeperException) cause).code()
                                                                .intValue();
                                                    } else if (cause instanceof ZKException) {
                                                        rcToReturn = ((ZKException) cause)
                                                                .getKeeperExceptionCode().intValue();
                                                    }
                                                    // :( properly we need dlog related response code.
                                                    callback.operationComplete(rcToReturn, null);
                                                    return;
                                                }
                                            }
                                        }

                                        private void complete() {
                                            if (0 == numChildren.decrementAndGet() && numFailures.get() == 0) {
                                                // update the cache only when fetch completed
                                                logSegmentCache.update(removedSegments, addedSegments);
                                                List<LogSegmentMetadata> segmentList;
                                                try {
                                                    segmentList = getCachedLogSegments(comparator);
                                                } catch (UnexpectedException e) {
                                                    callback.operationComplete(
                                                            KeeperException.Code.DATAINCONSISTENCY.intValue(),
                                                            null);
                                                    return;
                                                }
                                                callback.operationComplete(KeeperException.Code.OK.intValue(),
                                                        segmentList);
                                                notifyUpdatedLogSegments(segmentList);
                                                notifyOnOperationComplete();
                                            }
                                        }
                                    });
                        }
                    }
                }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        getListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        finalCallback.operationComplete(KeeperException.Code.CONNECTIONLOSS.intValue(), null);
    } catch (InterruptedException e) {
        getListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        finalCallback.operationComplete(KeeperException.Code.CONNECTIONLOSS.intValue(), null);
    }
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java

@Override
public void asyncDelete(final DeleteLedgerCallback callback, final Object ctx) {
    // Delete the managed ledger without closing, since we are not interested in gracefully closing cursors and
    // ledgers/*from  w w  w  .  java2  s  .co  m*/
    STATE_UPDATER.set(this, State.Fenced);

    List<ManagedCursor> cursors = Lists.newArrayList(this.cursors);
    if (cursors.isEmpty()) {
        // No cursors to delete, proceed with next step
        deleteAllLedgers(callback, ctx);
        return;
    }

    AtomicReference<ManagedLedgerException> cursorDeleteException = new AtomicReference<>();
    AtomicInteger cursorsToDelete = new AtomicInteger(cursors.size());
    for (ManagedCursor cursor : cursors) {
        asyncDeleteCursor(cursor.getName(), new DeleteCursorCallback() {
            @Override
            public void deleteCursorComplete(Object ctx) {
                if (cursorsToDelete.decrementAndGet() == 0) {
                    if (cursorDeleteException.get() != null) {
                        // Some cursor failed to delete
                        callback.deleteLedgerFailed(cursorDeleteException.get(), ctx);
                        return;
                    }

                    // All cursors deleted, continue with deleting all ledgers
                    deleteAllLedgers(callback, ctx);
                }
            }

            @Override
            public void deleteCursorFailed(ManagedLedgerException exception, Object ctx) {
                log.warn("[{}] Failed to delete cursor {}", name, cursor, exception);
                cursorDeleteException.compareAndSet(null, exception);
                if (cursorsToDelete.decrementAndGet() == 0) {
                    // Trigger callback only once
                    callback.deleteLedgerFailed(exception, ctx);
                }
            }
        }, null);
    }
}

From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java

protected void internalDeletePartitionedTopic(boolean authoritative, boolean force) {
    validateAdminAccessForTenant(topicName.getTenant());
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative);
    int numPartitions = partitionMetadata.partitions;
    if (numPartitions > 0) {
        final CompletableFuture<Void> future = new CompletableFuture<>();
        final AtomicInteger count = new AtomicInteger(numPartitions);
        try {/*  w ww. j av a2 s  .c om*/
            for (int i = 0; i < numPartitions; i++) {
                TopicName topicNamePartition = topicName.getPartition(i);
                pulsar().getAdminClient().persistentTopics().deleteAsync(topicNamePartition.toString(), force)
                        .whenComplete((r, ex) -> {
                            if (ex != null) {
                                if (ex instanceof NotFoundException) {
                                    // if the sub-topic is not found, the client might not have called create
                                    // producer or it might have been deleted earlier, so we ignore the 404 error.
                                    // For all other exception, we fail the delete partition method even if a single
                                    // partition is failed to be deleted
                                    if (log.isDebugEnabled()) {
                                        log.debug("[{}] Partition not found: {}", clientAppId(),
                                                topicNamePartition);
                                    }
                                } else {
                                    future.completeExceptionally(ex);
                                    log.error("[{}] Failed to delete partition {}", clientAppId(),
                                            topicNamePartition, ex);
                                    return;
                                }
                            } else {
                                log.info("[{}] Deleted partition {}", clientAppId(), topicNamePartition);
                            }
                            if (count.decrementAndGet() == 0) {
                                future.complete(null);
                            }
                        });
            }
            future.get();
        } catch (Exception e) {
            Throwable t = e.getCause();
            if (t instanceof PreconditionFailedException) {
                throw new RestException(Status.PRECONDITION_FAILED, "Topic has active producers/subscriptions");
            } else {
                throw new RestException(t);
            }
        }
    }

    // Only tries to delete the znode for partitioned topic when all its partitions are successfully deleted
    String path = path(PARTITIONED_TOPIC_PATH_ZNODE, namespaceName.toString(), domain(),
            topicName.getEncodedLocalName());
    try {
        globalZk().delete(path, -1);
        globalZkCache().invalidate(path);
        // we wait for the data to be synced in all quorums and the observers
        Thread.sleep(PARTITIONED_TOPIC_WAIT_SYNC_TIME_MS);
        log.info("[{}] Deleted partitioned topic {}", clientAppId(), topicName);
    } catch (KeeperException.NoNodeException nne) {
        throw new RestException(Status.NOT_FOUND, "Partitioned topic does not exist");
    } catch (KeeperException.BadVersionException e) {
        log.warn("[{}] Failed to delete partitioned topic {}: concurrent modification", clientAppId(),
                topicName);
        throw new RestException(Status.CONFLICT, "Concurrent modification");
    } catch (Exception e) {
        log.error("[{}] Failed to delete partitioned topic {}", clientAppId(), topicName, e);
        throw new RestException(e);
    }
}

From source file:com.vmware.photon.controller.deployer.xenon.workflow.DeploymentWorkflowService.java

private void migrateData(State currentState, List<VmService.State> managementVms,
        final String destinationProtocol) {
    Collection<DeploymentMigrationInformation> migrationInformation = HostUtils.getDeployerContext(this)
            .getDeploymentMigrationInformation();

    final AtomicInteger latch = new AtomicInteger(migrationInformation.size());
    final List<Throwable> errors = new BlockingArrayQueue<>();

    Set<InetSocketAddress> sourceServers = new HashSet<>();
    Set<InetSocketAddress> destinationServers = new HashSet<>();

    for (DeploymentMigrationInformation entry : migrationInformation) {
        if (sourceServers.size() == 0) {
            sourceServers.add(new InetSocketAddress(getHost().getPreferredAddress(), getHost().getPort()));
            for (VmService.State vm : managementVms) {
                destinationServers.add(new InetSocketAddress(vm.ipAddress, vm.deployerXenonPort));
            }/*from w  w w  .j a v  a2  s  .  c om*/
        }

        String factory = entry.factoryServicePath;
        if (!factory.endsWith("/")) {
            factory += "/";
        }

        CopyStateTaskService.State startState = new CopyStateTaskService.State();
        startState.sourceURIs = Collections.singletonList(getHost().getUri());
        startState.sourceFactoryLink = factory;
        startState.destinationURI = UriUtils.buildUri(destinationProtocol, managementVms.get(0).ipAddress,
                managementVms.get(0).deployerXenonPort, null, null);
        startState.destinationFactoryLink = factory;

        TaskUtils.startTaskAsync(this, CopyStateTaskFactoryService.SELF_LINK, startState,
                state -> TaskUtils.finalTaskStages.contains(state.taskState.stage),
                CopyStateTaskService.State.class, currentState.taskPollDelay,
                new FutureCallback<CopyStateTaskService.State>() {

                    @Override
                    public void onSuccess(@Nullable CopyStateTaskService.State result) {
                        switch (result.taskState.stage) {
                        case FINISHED:
                            break;
                        case FAILED:
                        case CANCELLED:
                            errors.add(new Throwable("service: " + result.documentSelfLink + " did not finish. "
                                    + result.taskState.failure.message));
                            break;
                        default:
                            errors.add(new Throwable("service: " + result.documentSelfLink
                                    + " ended in unexpected stage " + result.taskState.stage.name()));
                            break;
                        }

                        if (latch.decrementAndGet() == 0) {
                            if (!errors.isEmpty()) {
                                failTask(errors);
                            } else {
                                updateDeploymentServiceState(destinationServers, currentState,
                                        destinationProtocol);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        errors.add(t);
                        if (latch.decrementAndGet() == 0) {
                            failTask(errors);
                        }
                    }
                });
    }
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java

@SuppressWarnings("checkstyle:fallthrough")
private void deleteAllLedgers(DeleteLedgerCallback callback, Object ctx) {
    List<LedgerInfo> ledgers = Lists.newArrayList(ManagedLedgerImpl.this.ledgers.values());
    AtomicInteger ledgersToDelete = new AtomicInteger(ledgers.size());
    if (ledgers.isEmpty()) {
        // No ledgers to delete, proceed with deleting metadata
        deleteMetadata(callback, ctx);//  w  w w  .  j  a  v  a  2s. c o m
        return;
    }

    for (LedgerInfo ls : ledgers) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Deleting ledger {}", name, ls);
        }
        bookKeeper.asyncDeleteLedger(ls.getLedgerId(), (rc, ctx1) -> {
            switch (rc) {
            case BKException.Code.NoSuchLedgerExistsException:
                log.warn("[{}] Ledger {} not found when deleting it", name, ls.getLedgerId());
                // Continue anyway

            case BKException.Code.OK:
                if (ledgersToDelete.decrementAndGet() == 0) {
                    // All ledgers deleted, now remove ML metadata
                    deleteMetadata(callback, ctx);
                }
                break;

            default:
                // Handle error
                log.warn("[{}] Failed to delete ledger {} -- {}", name, ls.getLedgerId(),
                        BKException.getMessage(rc));
                int toDelete = ledgersToDelete.get();
                if (toDelete != -1 && ledgersToDelete.compareAndSet(toDelete, -1)) {
                    // Trigger callback only once
                    callback.deleteLedgerFailed(createManagedLedgerException(rc), ctx);
                }
            }
        }, null);
    }
}