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:org.artifactory.storage.db.binstore.service.BinaryStoreImpl.java

@Override
public void decrementNoDeleteLock(String sha1) {
    AtomicInteger usageCount = deleteProtectedBinaries.get(sha1);
    if (usageCount != null) {
        usageCount.decrementAndGet();
    }// ww w  . ja va 2 s .  c  o  m
}

From source file:org.talend.components.netsuite.client.NetSuiteClientServiceTest.java

@Test
public void testRetrying() throws Exception {

    clientService.setRetryCount(3);/*from   ww w . j  ava2s .  c  o m*/
    clientService.setRetryInterval(1);

    clientService.login();

    TypeDesc typeDesc = clientService.getMetaDataSource().getTypeInfo("RecordRef");

    RecordRef recordRef = new NsObjectComposer<RecordRef>(clientService.getMetaDataSource(), typeDesc)
            .composeObject();

    final DeleteResponse response = new DeleteResponse();
    response.setWriteResponse(createSuccessWriteResponse());

    final AtomicInteger counter = new AtomicInteger(3);

    when(port.delete(notNull(DeleteRequest.class))).thenAnswer(new Answer<DeleteResponse>() {

        @Override
        public DeleteResponse answer(InvocationOnMock invocation) throws Throwable {
            if (counter.decrementAndGet() > 0) {
                com.netsuite.webservices.test.platform.faults.InvalidSessionFault faultInfo = new com.netsuite.webservices.test.platform.faults.InvalidSessionFault();
                faultInfo.setCode(FaultCodeType.SESSION_TIMED_OUT);
                faultInfo.setMessage("Session timed out");
                InvalidSessionFault fault = new InvalidSessionFault(faultInfo.getMessage(), faultInfo);
                throw fault;
            }

            return response;
        }
    });

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    clientService.delete(recordRef);

    stopWatch.stop();

    verify(port, times(3)).login(notNull(LoginRequest.class));
    verify(port, times(3)).delete(notNull(DeleteRequest.class));

    assertTrue(stopWatch.getTime() >= 3 * clientService.getRetryInterval() * 1000);
}

From source file:org.springframework.amqp.rabbit.connection.AbstractConnectionFactoryTests.java

@Test
public void testWithListenerRegisteredAfterOpen() throws Exception {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);

    final AtomicInteger called = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    Connection con = connectionFactory.createConnection();
    assertEquals(0, called.get());//  www  .  ja va 2s  .c o m

    connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override
        public void onCreate(Connection connection) {
            called.incrementAndGet();
        }

        @Override
        public void onClose(Connection connection) {
            called.decrementAndGet();
        }

    }));
    assertEquals(1, called.get());

    con.close();
    assertEquals(1, called.get());
    verify(mockConnection, never()).close(anyInt());

    connectionFactory.createConnection();
    assertEquals(1, called.get());

    connectionFactory.destroy();
    assertEquals(0, called.get());
    verify(mockConnection, atLeastOnce()).close(anyInt());

    verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString());

}

From source file:org.talend.librariesmanager.ui.dialogs.ExternalModulesInstallDialogWithProgress.java

@Override
protected void launchIndividualDownload(final AtomicInteger enabledButtonCount, ModuleToInstall data,
        final Button button) {
    button.setEnabled(false);/* w w w  .  j a v a2s .  com*/
    enabledButtonCount.decrementAndGet();
    DownloadModuleRunnableWithLicenseDialog downloadModuleRunnable = new DownloadModuleRunnableWithLicenseDialog(
            Collections.singletonList(data), getShell());
    try {
        run(downloadModuleRunnable);
    } catch (InvocationTargetException e) {
        individualDownloadFailed(enabledButtonCount, button);
        // an error occured when fetching the modules, so report it to the user.
        ExceptionHandler.process(e);
    } catch (InterruptedException e) {
        individualDownloadFailed(enabledButtonCount, button);
        // the thread was interupted
        ExceptionHandler.process(e);
    } finally {// if button canceled then enable button
        if (getProgressMonitor().isCanceled()) {
            individualDownloadFailed(enabledButtonCount, button);
        } else {// keep button disabled and make download all button disabled if that was the last
            Display.getDefault().syncExec(new Runnable() {

                @Override
                public void run() {
                    if (!installAllBtn.isDisposed() && enabledButtonCount.get() == 0) {
                        installAllBtn.setEnabled(false);
                    }
                }
            });
        }
    }
}

From source file:org.voltdb.TableHelper.java

/**
 * Delete rows in a VoltDB table that has a bigint pkey where pkey values are odd.
 * Works best when pkey values are contiguous and start around 0.
 *
 * Exists mostly to force compaction on tables loaded with fillTableWithBigintPkey.
 * Though if you have an even number of sites, this won't work. It'll need to be
 * updated to delete some other pattern that's a bit more generic. Right now it
 * works great for my one-site testing./*  ww w.j a v  a 2 s  .co  m*/
 *
 */
public static long deleteEveryNRows(VoltTable table, Client client, int n) throws Exception {
    // find the primary key, assume first col if not found
    int pkeyColIndex = getBigintPrimaryKeyIndexIfExists(table);
    if (pkeyColIndex == -1) {
        pkeyColIndex = 0;
        assert (table.getColumnType(0).isInteger());
    }
    String pkeyColName = table.getColumnName(pkeyColIndex);

    VoltTable result = client
            .callProcedure("@AdHoc", String.format("select %s from %s order by %s desc limit 1;", pkeyColName,
                    TableHelper.getTableName(table), pkeyColName))
            .getResults()[0];
    long maxId = result.getRowCount() > 0 ? result.asScalarLong() : 0;
    System.out.printf("Deleting odd rows with pkey ids in the range 0-%d\n", maxId);

    // track outstanding responses so 10k can be out at a time
    final AtomicInteger outstanding = new AtomicInteger(0);
    final AtomicLong deleteCount = new AtomicLong(0);

    ProcedureCallback callback = new ProcedureCallback() {
        @Override
        public void clientCallback(ClientResponse clientResponse) throws Exception {
            outstanding.decrementAndGet();
            if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
                System.out.println("Error in deleter callback:");
                System.out.println(((ClientResponseImpl) clientResponse).toJSONString());
                assert (false);
            }
            VoltTable result = clientResponse.getResults()[0];
            long modified = result.asScalarLong();
            assert (modified <= 1);
            deleteCount.addAndGet(modified);
        }
    };

    // delete 100k rows at a time until nothing comes back
    long deleted = 0;
    final String deleteProcName = table.m_extraMetadata.name.toUpperCase() + ".delete";
    for (int i = 1; i <= maxId; i += n) {
        client.callProcedure(callback, deleteProcName, i);
        outstanding.incrementAndGet();
        deleted++;
        if ((deleted % 100000) == 0) {
            System.out.printf("Sent %d total delete invocations (%.1f%% of range).\n", deleted,
                    (i * 100.0) / maxId);
        }
        // block while 1000 txns are outstanding
        while (outstanding.get() >= 1000) {
            Thread.yield();
        }
    }
    // block until all calls have returned
    while (outstanding.get() > 0) {
        Thread.yield();
    }
    System.out.printf("Deleted %d odd rows\n", deleteCount.get());

    return deleteCount.get();
}

From source file:fr.wseduc.webutils.email.SendInBlueSender.java

@Override
protected void sendEmail(JsonObject json, final Handler<Message<JsonObject>> handler) {
    if (json == null || json.getArray("to") == null || json.getString("from") == null
            || json.getString("subject") == null || json.getString("body") == null) {
        handler.handle(new ResultMessage().error("invalid.parameters"));
        return;/*from w w w .jav a  2s. co  m*/
    }
    if (splitRecipients && json.getArray("to").size() > 1) {
        final AtomicInteger count = new AtomicInteger(json.getArray("to").size());
        final AtomicBoolean success = new AtomicBoolean(true);
        final JsonArray errors = new JsonArray();
        final Handler<Message<JsonObject>> h = new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> message) {
                if (!"ok".equals(message.body().getString("status"))) {
                    success.set(false);
                    errors.addString(message.body().getString("message"));
                }
                if (count.decrementAndGet() == 0) {
                    if (success.get()) {
                        handler.handle(new ResultMessage());
                    } else {
                        handler.handle(new ResultMessage().error(errors.encode()));
                    }
                }
            }
        };
        for (Object to : json.getArray("to")) {
            send(json.copy().putArray("to", new JsonArray().addString(to.toString())), h);
        }
    } else {
        send(json, handler);
    }
}

From source file:org.waveprotocol.wave.federation.xmpp.XmppFederationRemote.java

/**
 * Handles a wavelet update message from a foreign Federation Host. Passes the
 * message to the local waveserver (synchronously) and replies.
 *
 * @param updateMessage the incoming XMPP message.
 * @param responseCallback response callback for acks and errors
 */// ww  w . j ava  2 s. co  m
public void update(final Message updateMessage, final PacketCallback responseCallback) {
    final Element receiptRequested = updateMessage.getChildElement("request",
            XmppNamespace.NAMESPACE_XMPP_RECEIPTS);

    // Check existence of <event>
    Element event = updateMessage.getChildElement("event", XmppNamespace.NAMESPACE_PUBSUB_EVENT);
    if (event == null) {
        responseCallback.error(FederationErrors.badRequest("Event element missing from message"));
        return;
    }

    // Check existence of <items> within <event>
    Element items = event.element("items");
    if (items == null) {
        responseCallback.error(FederationErrors.badRequest("Items element missing from update message"));
        return;
    }

    // Complain if no items have been included.
    List<Element> elements = XmppUtil.toSafeElementList(items.elements("item"));
    if (elements.isEmpty()) {
        responseCallback.error(FederationErrors.badRequest("No items included"));
        return;
    }

    // Create a callback latch counter and corresponding countDown runnable.
    // When the latch reaches zero, send receipt (if it was requested).
    final AtomicInteger callbackCount = new AtomicInteger(1);
    final Runnable countDown = new Runnable() {
        @Override
        public void run() {
            if (callbackCount.decrementAndGet() == 0 && receiptRequested != null) {
                Message response = XmppUtil.createResponseMessage(updateMessage);
                response.addChildElement("received", XmppNamespace.NAMESPACE_XMPP_RECEIPTS);
                responseCallback.run(response);
            }
        }
    };

    WaveletFederationListener.WaveletUpdateCallback callback = new WaveletFederationListener.WaveletUpdateCallback() {
        @Override
        public void onSuccess() {
            countDown.run();
        }

        @Override
        public void onFailure(FederationError error) {
            // Note that we don't propogate the error, we just ack the stanza
            // and continue.
            // TODO(thorogood): We may want to rate-limit misbehaving servers
            // that are sending us invalid/malicious data.
            LOG.warning("Incoming XMPP waveletUpdate failure: " + error);
            countDown.run();
        }
    };

    // We must call callback once on every iteration to ensure that we send
    // response if receiptRequested != null.
    for (Element item : elements) {
        Element waveletUpdate = item.element("wavelet-update");

        if (waveletUpdate == null) {
            callback.onFailure(FederationErrors
                    .badRequest("wavelet-update element missing from message: " + updateMessage));
            continue;
        }

        final WaveletName waveletName;
        try {
            waveletName = XmppUtil.waveletNameCodec
                    .uriToWaveletName(waveletUpdate.attributeValue("wavelet-name"));
        } catch (EncodingException e) {
            callback.onFailure(FederationErrors.badRequest(
                    "Couldn't decode wavelet name: " + waveletUpdate.attributeValue("wavelet-name")));
            continue;
        }

        WaveletFederationListener listener = updatesListenerFactory
                .listenerForDomain(waveletName.waveletId.getDomain());

        // Submit all applied deltas to the domain-focused listener.
        ImmutableList.Builder<ByteString> builder = ImmutableList.builder();
        for (Element appliedDeltaElement : XmppUtil
                .toSafeElementList(waveletUpdate.elements("applied-delta"))) {
            builder.add(Base64Util.decode(appliedDeltaElement.getText()));
        }
        ImmutableList<ByteString> deltas = builder.build();
        if (!deltas.isEmpty()) {
            callbackCount.incrementAndGet(); // Increment required callbacks.
            listener.waveletDeltaUpdate(waveletName, deltas, callback);
        }

        // Optionally submit any received last committed notice.
        Element commitNoticeElement = waveletUpdate.element("commit-notice");
        if (commitNoticeElement != null) {
            ProtocolHashedVersion version = ProtocolHashedVersion.newBuilder()
                    .setHistoryHash(Base64Util.decode(commitNoticeElement.attributeValue("history-hash")))
                    .setVersion(Long.parseLong(commitNoticeElement.attributeValue("version"))).build();
            callbackCount.incrementAndGet(); // Increment required callbacks.
            listener.waveletCommitUpdate(waveletName, version, callback);
        }
    }

    // Release sentinel so that 'expected' callbacks from the WS don't invoke
    // sending a receipt.
    countDown.run();
}

From source file:com.zimbra.cs.servlet.ContextPathBasedThreadPoolBalancerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Determine whether to allow or suspend request
    boolean suspend = shouldSuspend(request);

    // Suspend request
    if (suspend) {
        Continuation continuation = ContinuationSupport.getContinuation(request);
        HttpServletRequest hreq = (HttpServletRequest) request;
        ZimbraServlet.addRemoteIpToLoggingContext(hreq);
        ZimbraServlet.addUAToLoggingContext(hreq);
        ZimbraLog.clearContext();/*from   ww w  .  j  a v a 2 s. c  o  m*/
        continuation.setTimeout(suspendMs);
        continuation.suspend();
        return;
    }

    // Allow request
    String contextPath = getContextPath(request);
    try {
        // Start tracking request
        AtomicInteger i = activeRequestsByContextPath.get(contextPath);
        if (i == null) {
            i = new AtomicInteger(1);
            activeRequestsByContextPath.put(contextPath, i);
        } else {
            i.incrementAndGet();
        }
        //            ZimbraLog.misc.debug("%s concurrency=%d", contextPath, i.get());

        // Perform default operation
        chain.doFilter(request, response);

    } finally {
        // Stop tracking request
        AtomicInteger i = activeRequestsByContextPath.get(contextPath);
        i.decrementAndGet();
        //            ZimbraLog.misc.debug("%s concurrency=%d", contextPath, i.get());
    }
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorEventListener.java

@Override
protected void processEvent(Event event) {
    if (event instanceof ConnectionStatusEvent) {
        ConnectionStatusEvent connectionStatusEvent = (ConnectionStatusEvent) event;
        String channelId = connectionStatusEvent.getChannelId();
        Integer metaDataId = connectionStatusEvent.getMetaDataId();
        String information = connectionStatusEvent.getMessage();
        Timestamp timestamp = new Timestamp(event.getDateTime());

        String connectorId = channelId + "_" + metaDataId;

        ConnectionStatusEventType eventType = connectionStatusEvent.getState();

        ConnectionStatusEventType connectionStatusEventType = eventType;
        Integer connectorCount = null;
        Integer maximum = null;//  www  .j  ava 2 s. c o  m

        if (event instanceof ConnectorCountEvent) {
            ConnectorCountEvent connectorCountEvent = (ConnectorCountEvent) connectionStatusEvent;

            maximum = connectorCountEvent.getMaximum();
            Boolean increment = connectorCountEvent.isIncrement();

            if (maximum != null) {
                maxConnectionMap.put(connectorId, maximum);
            } else {
                maximum = maxConnectionMap.get(connectorId);
            }

            AtomicInteger count = connectorCountMap.get(connectorId);

            if (count == null) {
                count = new AtomicInteger();
                connectorCountMap.put(connectorId, count);
            }

            if (increment != null) {
                if (increment) {
                    count.incrementAndGet();
                } else {
                    count.decrementAndGet();
                }
            }

            connectorCount = count.get();

            if (connectorCount == 0) {
                connectionStatusEventType = ConnectionStatusEventType.IDLE;
            } else {
                connectionStatusEventType = ConnectionStatusEventType.CONNECTED;
            }
        }

        String stateString = null;
        if (connectionStatusEventType.isState()) {
            Color color = getColor(connectionStatusEventType);
            stateString = connectionStatusEventType.toString();
            if (connectorCount != null) {
                if (maximum != null && connectorCount.equals(maximum)) {
                    stateString += " <font color='red'>(" + connectorCount + ")</font>";
                } else if (connectorCount > 0) {
                    stateString += " (" + connectorCount + ")";
                }
            }

            connectorStateMap.put(connectorId, new Object[] { color, stateString });
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        String channelName = "";
        String connectorType = "";

        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelId)) {
                channelLog = connectorInfoLogs.get(channelId);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            if (metaDataId == 0) {
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundDataType().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundDataType().toString() + ")";
            } else {
                Connector connector = getConnectorFromMetaDataId(channel.getDestinationConnectors(),
                        metaDataId);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();
            }
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelId, channelLog);
            }
        }

    }
}

From source file:com.indeed.lsmtree.recordlog.TestBlockCompressedRecordFile.java

public void testRandom() throws IOException {
    final BlockCompressedRecordFile<String> recordFile = createBlockCache();
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override/*w  ww.j av a  2  s.  co m*/
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < 10000000; i++) {
                        int rand = r.nextInt(positions.size());
                        assertTrue(recordFile.get(positions.get(rand)).equals(strings.get(rand)));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    recordFile.close();
}