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

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

Introduction

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

Prototype

public AtomicInteger() 

Source Link

Document

Creates a new AtomicInteger with initial value 0 .

Usage

From source file:com.jgoetsch.eventtrader.source.SocketIOWebSocketMsgSource.java

@Override
protected void receiveMsgs() {
    final String baseThreadName = Thread.currentThread().getName();
    ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT);
    ThreadFactory threadFactory = new ThreadFactory() {
        private AtomicInteger n = new AtomicInteger();

        public Thread newThread(Runnable r) {
            return new Thread(r, baseThreadName + "-w-" + n.incrementAndGet());
        }//ww  w. j  av  a  2 s  .  c  o m
    };
    bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(threadFactory), Executors.newCachedThreadPool(threadFactory)));

    try {
        URI url = new URI(getTokenUrl());

        final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url,
                WebSocketVersion.V13, null, false, null);

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new HttpResponseDecoder());
                pipeline.addLast("encoder", new HttpRequestEncoder());
                pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker));
                pipeline.addLast("sio-handler", new SocketIOClientHandler());
                return pipeline;
            }
        });

        ChannelFuture future = bootstrap
                .connect(new InetSocketAddress(url.getHost(), url.getPort() == -1 ? 80 : url.getPort()));
        future.syncUninterruptibly();
        ch = future.getChannel();
        handshaker.handshake(ch).syncUninterruptibly();
        ch.getCloseFuture().awaitUninterruptibly();
    } catch (URISyntaxException use) {
        log.error("Invalid URL: {}", getUrl(), use);
    } catch (Exception e) {
        log.error("Error getting token", e);
    } finally {
        if (ch != null)
            ch.close();
        bootstrap.releaseExternalResources();
    }
}

From source file:com.datasnap.android.integration.IntegrationManagerTest.java

@Test
public void testIntegrationSelection() {

    final String key = "Some Integration";

    // create a settings cache that will insert fake provider settings for this key
    SettingsCache settingsCache = new SettingsCache(context, layer, Defaults.SETTINGS_CACHE_EXPIRY) {
        @Override/*from w w w .j  a  v  a 2  s .c o  m*/
        public EasyJSONObject getSettings() {
            // get them directly from the server with blocking
            EasyJSONObject settings = requester.fetchSettings();
            if (settings != null)
                settings.putObject(key, new JSONObject());
            return settings;
        }
    };

    // make the sure the settings cache has nothing in it right now
    settingsCache.reset();

    IntegrationManager integrationManager = new IntegrationManager(settingsCache);

    // removes all the providers
    integrationManager.getIntegrations().clear();

    final AtomicInteger identifies = new AtomicInteger();
    final AtomicInteger tracks = new AtomicInteger();
    final AtomicInteger screens = new AtomicInteger();
    final AtomicInteger aliases = new AtomicInteger();

    Integration provider = new SimpleIntegration() {
        @Override
        public void onCreate(Context context) {
            ready();
        }

        @Override
        public String getKey() {
            return key;
        }

        @Override
        public void validate(EasyJSONObject settings) throws InvalidSettingsException {
        }

        @Override
        public void identify(Identify identify) {
            identifies.addAndGet(1);
        }

        @Override
        public void track(Track track) {
            tracks.addAndGet(1);
        }

        @Override
        public void screen(Screen screen) {
            screens.addAndGet(1);
        }

        @Override
        public void alias(Alias alias) {
            aliases.addAndGet(1);
        }
    };

    // add a simple adding provider
    integrationManager.addIntegration(provider);

    // get the settings from the server, which won't include this provider
    integrationManager.refresh();

    // call the method that enables it
    integrationManager.onCreate(context);

    //
    // Test the no specific context.providers added
    //

    integrationManager.identify(TestCases.identify());
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager.track(TestCases.track());
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.screen(TestCases.screen());
    assertThat(screens.get()).isEqualTo(1);

    integrationManager.alias(TestCases.alias());
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Assemble test values
    //

    Identify identify = TestCases.identify();

    String userId = identify.getUserId();
    Traits traits = identify.getTraits();
    Calendar timestamp = Calendar.getInstance();

    Track track = TestCases.track();

    String event = TestCases.track().getEvent();
    Props properties = track.getProperties();

    Alias alias = TestCases.alias();

    String from = alias.getPreviousId();
    String to = alias.getUserId();

    //
    // Test the integrations.all = false setting default to false
    //

    Options allFalseOptions = new Options().setTimestamp(timestamp).setIntegration("all", false);
    EasyJSONObject bundledIntegrations = new EasyJSONObject();

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, allFalseOptions));
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager.track(new Track(userId, event, properties, bundledIntegrations, allFalseOptions));
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, allFalseOptions));
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Test the integrations[integration.key] = false turns it off
    //

    Options integrationFalseOptions = new Options().setTimestamp(timestamp).setIntegration(key, false);

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, integrationFalseOptions));
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager
            .track(new Track(userId, event, properties, bundledIntegrations, integrationFalseOptions));
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, integrationFalseOptions));
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Test the integrations[integration.key] = true, All=false keeps it on
    //

    Options integrationTrueOptions = new Options().setTimestamp(timestamp).setIntegration("all", false)
            .setIntegration(key, true);

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, integrationTrueOptions));
    assertThat(identifies.get()).isEqualTo(2);

    integrationManager.track(new Track(userId, event, properties, bundledIntegrations, integrationTrueOptions));
    assertThat(tracks.get()).isEqualTo(2);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, integrationTrueOptions));
    assertThat(aliases.get()).isEqualTo(2);
}

From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testRetries() throws InterruptedException {
    Product product = new Product();
    product.setId(123L);//from ww  w  .j  av a  2  s.  com
    product.setName("Tv");
    productRepository.save(product);
    Product savedProduct = productRepository.findOne(123L);
    assertEquals(savedProduct, product);

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(123L, UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}

From source file:cn.edu.zjnu.acm.judge.core.Judger.java

@PostConstruct
public void init() {
    final ThreadGroup group = new ThreadGroup("judge group");
    final AtomicInteger countet = new AtomicInteger();
    final ThreadFactory threadFactory = runnable -> new Thread(group, runnable,
            "judge thread " + countet.incrementAndGet());
    executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), threadFactory);
}

From source file:com.consol.citrus.demo.devoxx.service.ReportService.java

/**
 * Reset all reports in memory./*from  w w  w. ja v  a  2  s. c o  m*/
 */
public void reset() {
    report.clear();
    produced.clear();

    report.put("chocolate", new AtomicInteger());
    report.put("caramel", new AtomicInteger());
    report.put("blueberry", new AtomicInteger());
}

From source file:io.uploader.drive.drive.DriveOperations.java

private static File createDirectoryIfNotExist(Drive client, final File parent, String title) throws Throwable {
    File driveDirectory = null;//w ww  .j a va 2 s. co  m
    AtomicInteger tryCounter = new AtomicInteger();
    while (true) {
        try {
            FileList dirs = DriveUtils.findDirectoriesWithTitle(client, title, DriveUtils.newId(parent),
                    (Integer) null);
            if (dirs.getItems() == null || dirs.getItems().isEmpty()) {
                logger.info(String.format("The directory %s does not exists%s. It will be created.", title,
                        ((parent == null) ? ("") : (" (under " + parent.getTitle() + ")"))));
                driveDirectory = DriveUtils.insertDirectory(client, title, null, DriveUtils.newId(parent));
            } else if (dirs.getItems().size() > 1) {
                throw new IllegalStateException(
                        "There are " + dirs.size() + " directories with the name " + title + "...");
            } else {
                driveDirectory = dirs.getItems().get(0);
            }
            break;
        } catch (Throwable e) {
            dealWithException(e, tryCounter);
        }
    }
    return driveDirectory;
}

From source file:com.adaptris.core.services.jdbc.JdbcBatchingDataCaptureService.java

@Override
protected long finishUpdate(PreparedStatement insert) throws SQLException {
    long rowsUpdated = rowsUpdated(insert.executeBatch());
    counter.set(new AtomicInteger());
    return rowsUpdated;
}

From source file:com.ethercamp.harmony.service.WalletService.java

@PostConstruct
public void init() {
    addresses.clear();// w  w w.  java2s. c o  m

    final AtomicInteger index = new AtomicInteger();
    Arrays.asList(keystore.listStoredKeys())
            .forEach(a -> addresses.put(cleanAddress(a), "Account " + index.incrementAndGet()));

    fileSystemWalletStore.fromStore().stream().forEach(a -> addresses.put(a.address, a.name));

    // workaround issue in ethereumJ-core, where single miner could never got sync done event
    if (config.minerStart()) {
        subscribeOnce();
    } else {
        ethereum.addListener(new EthereumListenerAdapter() {
            @Override
            public void onSyncDone(SyncState state) {
                if (state == SyncState.UNSECURE || state == SyncState.COMPLETE) {
                    subscribeOnce();
                }
            }
        });
    }
}

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;//from w w w. j a  va  2 s . c  om

        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:automenta.climatenet.ImportKML.java

public void transformKML(String layer, String urlString, ElasticSpacetime st, final GISVisitor visitor)
        throws Exception {
    URL url = new URL(urlString);
    this.layer = layer;

    KmlReader reader = new KmlReader(url, proxy);
    reader.setRewriteStyleUrls(true);//from   ww  w .  j  av  a 2  s . c o  m

    SimpleField layerfield = new SimpleField("layer", Type.STRING);
    layerfield.setLength(32);

    final AtomicInteger exceptions = new AtomicInteger();
    final Set<Class> exceptionClass = new HashSet();

    serial = 1;
    path.clear();

    visitor.start(layer);

    do {

        //for (IGISObject go; (go = reader.read()) != null;) {
        // do something with the gis object; e.g. check for placemark, NetworkLink, etc.
        try {

            IGISObject go = reader.read();
            if (go == null) {
                break;
            }

            if (go instanceof DocumentStart) {
                DocumentStart ds = (DocumentStart) go;

                path.add(layer);

            }

            if (go instanceof ContainerEnd) {
                path.removeLast();
            }

            if ((go instanceof ContainerStart) || (go instanceof Feature)) {
                serial++;
            }

            if (!visitor.on(go, getPath(path))) {
                break;
            }

            //add to the path after container start is processed
            if (go instanceof ContainerStart) {
                ContainerStart cs = (ContainerStart) go;
                //TODO startTime?
                //System.out.println(cs + " " + cs.getId());
                String i = getSerial(layer, serial);
                path.add(i);
            }

        } catch (Throwable t) {
            System.err.println(t);
            exceptions.incrementAndGet();
            exceptionClass.add(t.getClass());
        }
    } while (true);

    // get list of network links that were retrieved from step above
    Set<URI> networkLinks = new HashSet(reader.getNetworkLinks());

    reader.close();

    if (!networkLinks.isEmpty()) {

        // Now import features from all referenced network links.
        // if Networklinks have nested network links then they will be added to end
        // of the list and processed one after another. The handleEvent() callback method
        // below will be called with each feature (i.e. Placemark, GroundOverlay, etc.)
        // as it is processed in the target KML resources.
        reader.importFromNetworkLinks(new KmlReader.ImportEventHandler() {
            public boolean handleEvent(UrlRef ref, IGISObject gisObj) {

                // if gisObj instanceOf Feature, GroundOverlay, etc.
                // do something with the gisObj
                // return false to abort the recursive network link parsing
                /*if (visited.contains(ref))
                 return false;*/
                //System.out.println("Loading NetworkLink: " + ref + " " + gisObj);
                String r = ref.toString();
                boolean pathChanged = false;
                if (!(!path.isEmpty()) && (path.getLast().equals(r))) {
                    path.add(ref.toString());
                    pathChanged = true;
                }

                serial++;

                try {
                    visitor.on(gisObj, getPath(path));
                } catch (Throwable t) {
                    System.err.println(t);
                }

                if (pathChanged) {
                    path.removeLast();
                }

                return true;
            }

            @Override
            public void handleError(URI uri, Exception excptn) {
                exceptions.incrementAndGet();
                exceptionClass.add(excptn.getClass());
            }

        });

    }

    if (exceptions.get() > 0) {
        System.err.println("  Exceptions: " + exceptions + " of " + exceptionClass);
    }

    visitor.end();

}