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(int initialValue) 

Source Link

Document

Creates a new AtomicInteger with the given initial value.

Usage

From source file:jurls.core.becca.DefaultZiptie.java

public static double getGeneralizedMean(RealMatrix c, double exponent, int rowStart, int rowEnd, int colStart,
        int colEnd) {
    AtomicDouble s = new AtomicDouble(0);
    AtomicInteger n = new AtomicInteger(0);
    c.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
        @Override/* ww w.  j av a 2 s .  c om*/
        public void visit(int row, int column, double value) {
            s.addAndGet(Math.pow(value, exponent));
            n.incrementAndGet();
        }
    }, rowStart, rowEnd, colStart, colEnd);

    return (1.0 / n.doubleValue()) * Math.pow(s.doubleValue(), 1.0 / exponent);
}

From source file:org.jasig.ssp.util.importer.job.staging.PostgresStagingTableWriter.java

@Override
public void write(final List<? extends RawItem> items) {

    NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    String fileName = items.get(0).getResource().getFilename();
    final String[] tableName = fileName.split("\\.");

    Integer batchStart = (Integer) (stepExecution.getExecutionContext().get("batchStart") == null ? null
            : stepExecution.getExecutionContext().get("batchStart"));
    Integer batchStop = (Integer) (stepExecution.getExecutionContext().get("batchStop") == null ? null
            : stepExecution.getExecutionContext().get("batchStop"));
    Object currentEntity = stepExecution.getExecutionContext().get("currentEntity");

    if (currentEntity == null || !currentEntity.equals(tableName[0])) {
        batchStart = 0;//  ww  w. j  a v  a2  s.  c o m
        batchStop = items.size() - 1;
        currentEntity = tableName[0];
        stepExecution.getExecutionContext().put("currentEntity", currentEntity);
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    } else {
        batchStart = batchStop + 1;
        batchStop = (Integer) batchStart + items.size() - 1;
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    }

    RawItem firstItem = items.get(0);
    Resource firstItemResource = firstItem.getResource();

    if (currentResource == null || !(this.currentResource.equals(firstItemResource))) {
        this.orderedHeaders = writeHeader(firstItem);
        this.currentResource = firstItemResource;
    }

    StringBuilder insertSql = new StringBuilder();
    insertSql.append("INSERT INTO stg_" + tableName[0] + " (batch_id,");
    StringBuilder valuesSqlBuilder = new StringBuilder();
    valuesSqlBuilder.append(" VALUES (?,");
    for (String header : this.orderedHeaders) {
        insertSql.append(header).append(",");
        valuesSqlBuilder.append("?").append(",");
    }
    insertSql.setLength(insertSql.length() - 1); // trim comma
    valuesSqlBuilder.setLength(valuesSqlBuilder.length() - 1); // trim comma
    insertSql.append(")");
    valuesSqlBuilder.append(");");
    insertSql.append(valuesSqlBuilder);

    final AtomicInteger batchStartRef = new AtomicInteger(batchStart);
    final String sql = insertSql.toString();

    jdbcTemplate.getJdbcOperations().execute(sql, new PreparedStatementCallback() {
        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (RawItem item : items) {
                final List<Object> paramsForLog = new ArrayList(orderedHeaders.length);
                int counter = 1;
                paramsForLog.add(batchStartRef.get());
                StatementCreatorUtils.setParameterValue(ps, counter, SqlTypeValue.TYPE_UNKNOWN,
                        batchStartRef.getAndIncrement());
                counter++;
                for (String header : orderedHeaders) {
                    final Map<String, String> record = item.getRecord();
                    String value = record.get(header);
                    final Integer sqlType = metadataRepository.getRepository().getColumnMetadataRepository()
                            .getColumnMetadata(new ColumnReference(tableName[0], header)).getJavaSqlType();
                    paramsForLog.add(value);
                    StatementCreatorUtils.setParameterValue(ps, counter, sqlType, value);
                    counter++;
                }
                sayQuery(sql, paramsForLog);
                ps.addBatch();
            }
            return ps.executeBatch();
        }
    });

    batchStart = batchStartRef.get();

    say("******CHUNK POSTGRES******");
}

From source file:org.uimafit.factory.ExternalResourceFactoryTest.java

@Test
public void testDirectInjection() throws Exception {
    // Create analysis enginge description
    AnalysisEngineDescription desc = createPrimitiveDescription(DummyAE2.class);

    // Bind external resources for DummyAE
    bindResources(desc);/*w  w  w.j a va2  s . c  o  m*/

    // Bind external resources for DummyAE2 - necessary because autowiring is disabled
    bindExternalResource(desc, DummyAE2.RES_INJECTED_POJO1, "pojoName1");
    bindExternalResource(desc, DummyAE2.RES_INJECTED_POJO2, "pojoName2");

    // Create a custom resource manager that allows to inject any Java object as an external
    // dependency
    final Map<String, Object> externalContext = new HashMap<String, Object>();
    externalContext.put("pojoName1", "Just an injected POJO");
    externalContext.put("pojoName2", new AtomicInteger(5));

    SimpleNamedResourceManager resMgr = new SimpleNamedResourceManager();
    resMgr.setExternalContext(externalContext);
    assertFalse(resMgr.isAutoWireEnabled());

    AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(desc, resMgr, null);
    assertNotNull(ae);

    ae.process(ae.newJCas());
}

From source file:com.vgi.mafscaling.LogPlay.java

private void initialize() {
    lastRow = logDataTable.getRowCount() - 1;
    playNext = new AtomicInteger(1);
    playIcon = new ImageIcon(getClass().getResource("/play.png"));
    pauseIcon = new ImageIcon(getClass().getResource("/pause.png"));
    zeroInsets.put("Button.contentMargins", insets0);
    timer = new Timer(timerDelay, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            progressBar.setValue(progressBar.getValue() + playNext.get());
        }/*from   w  w w  . ja  v  a 2  s .c o m*/
    });

    JPanel dataPanel = new JPanel();
    GridBagLayout gbl_dataPanel = new GridBagLayout();
    gbl_dataPanel.columnWidths = new int[] { 0 };
    gbl_dataPanel.rowHeights = new int[] { 0, 1 };
    gbl_dataPanel.columnWeights = new double[] { 1.0 };
    gbl_dataPanel.rowWeights = new double[] { 0.0, 1.0 };
    dataPanel.setLayout(gbl_dataPanel);
    getContentPane().add(dataPanel);

    createSelectionPanel(dataPanel);
    createPlayer(dataPanel);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            timer.stop();
            synchronized (lock) {
                for (TableHolder t : tables)
                    t.table.dispose();
                tables.clear();
            }
            logView.disposeLogView();
        }
    });

    pack();
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setIconImage((new ImageIcon(getClass().getResource("/player.png"))).getImage());
    setResizable(false);
    setLocationRelativeTo(SwingUtilities.windowForComponent(logView));
    setVisible(true);
}

From source file:crawl.SphinxWrapper.java

protected void resetCounter() {
    countFetched = new AtomicInteger(0);
    countKept = new AtomicInteger(0);
}

From source file:com.chessix.vas.web.AccountController.java

@RequestMapping(value = "/{clasId}/range/from/{start}/count/{count}", method = RequestMethod.POST)
public DeferredResult<Object> createAccounts(@PathVariable final String clasId,
        @PathVariable final String start, @PathVariable final String count) {
    log.info("createAccounts({},{},{})", clasId, start, count);
    final ActorRef clas = clasService.getClas(clasId);
    final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
    final int countValue = Integer.parseInt(count);

    if (countValue > MAX_ACCOUNTS_IN_BATCH) {
        deferredResult//w  w  w. ja  v a2 s  . c  o m
                .setErrorResult(String.format("count %s is to large (> %d)", count, MAX_ACCOUNTS_IN_BATCH));
        return deferredResult;
    }

    if (clas != null) {
        final List<AccountCreated> results = Collections.synchronizedList(new LinkedList<AccountCreated>());
        final AtomicInteger resultsCounter = new AtomicInteger(0);

        for (int i = Integer.parseInt(start); i < Integer.parseInt(start) + countValue; i++) {
            final String accountId = Integer.toString(i);
            log.debug("createAccounts() : create {}", accountId);
            final Future<Object> future = Patterns.ask(clas,
                    new CreateAccount.RequestBuilder(clasId).accountId(accountId).build(),
                    timeout * countValue);
            future.onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(final Object result) {
                    log.info("createAccount({}) : result: {}", clasId, result);
                    final CreateAccount.Response response = (CreateAccount.Response) result;
                    results.add(new AccountCreated(clasId, response.getAccountId(), true,
                            String.format("Account %s created", accountId)));

                    // check if all values are received
                    if (resultsCounter.incrementAndGet() >= countValue) {
                        deferredResult.setResult(results);
                    }

                }
            }, system.dispatcher());
            future.onFailure(new OnFailure() {
                @Override
                public void onFailure(final Throwable arg) throws Throwable {
                    log.error("onFailure", arg);
                    deferredResult
                            .setErrorResult(new AccountCreated(clasId, null, false, arg.getLocalizedMessage()));
                }
            }, system.dispatcher());
        }
    } else {
        deferredResult.setErrorResult(new AccountCreated(clasId, null, false, "CLAS does not exist"));
    }
    return deferredResult;
}

From source file:com.spotify.heroic.shell.task.DeleteKeys.java

private AsyncFuture<Void> doDelete(final ShellIO io, final Parameters params, final MetricBackendGroup group,
        final QueryOptions options, final Stream<BackendKey> keys) {
    final StreamCollector<Pair<BackendKey, Long>, Void> collector = new StreamCollector<Pair<BackendKey, Long>, Void>() {
        @Override//  w w w  .j a  v a  2s.  com
        public void resolved(Pair<BackendKey, Long> result) throws Exception {
            if (params.verbose) {
                synchronized (io) {
                    io.out().println("Deleted: " + result.getLeft() + " (" + result.getRight() + ")");
                    io.out().flush();
                }
            }
        }

        @Override
        public void failed(Throwable cause) throws Exception {
            synchronized (io) {
                io.out().println("Delete Failed: " + cause);
                cause.printStackTrace(io.out());
                io.out().flush();
            }
        }

        @Override
        public void cancelled() throws Exception {
        }

        @Override
        public Void end(int resolved, int failed, int cancelled) throws Exception {
            io.out().println("Finished (resolved: " + resolved + ", failed: " + failed + ", " + "cancelled: "
                    + cancelled + ")");
            io.out().flush();
            return null;
        }
    };

    final AtomicInteger outstanding = new AtomicInteger(params.parallelism);

    final Object lock = new Object();

    final ResolvableFuture<Void> future = async.future();

    final Iterator<BackendKey> it = keys.iterator();

    for (int i = 0; i < params.parallelism; i++) {
        async.call(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                final BackendKey k;

                synchronized (lock) {
                    k = it.hasNext() ? it.next() : null;
                }

                if (k == null) {
                    if (outstanding.decrementAndGet() == 0) {
                        future.resolve(null);
                    }

                    return null;
                }

                deleteKey(group, k, options).onDone(new FutureDone<Pair<BackendKey, Long>>() {
                    @Override
                    public void failed(Throwable cause) throws Exception {
                        collector.failed(cause);
                    }

                    @Override
                    public void resolved(Pair<BackendKey, Long> result) throws Exception {
                        collector.resolved(result);
                    }

                    @Override
                    public void cancelled() throws Exception {
                        collector.cancelled();
                    }
                }).onFinished(this::call);

                return null;
            }
        });
    }

    return future.onFinished(keys::close);
}

From source file:com.spotify.helios.agent.TaskHistoryWriter.java

public TaskHistoryWriter(final String hostname, final ZooKeeperClient client, final Path backingFile)
        throws IOException, InterruptedException {
    this.hostname = hostname;
    this.client = client;
    this.backingStore = PersistentAtomicReference.create(backingFile,
            new TypeReference<ConcurrentMap<JobId, Deque<TaskStatusEvent>>>() {
            }, new Supplier<ConcurrentMap<JobId, Deque<TaskStatusEvent>>>() {
                @Override/* w w  w .ja v a2s. co m*/
                public ConcurrentMap<JobId, Deque<TaskStatusEvent>> get() {
                    return Maps.newConcurrentMap();
                }
            });
    this.items = backingStore.get();

    // Clean out any errant null values.  Normally shouldn't have any, but we did have a few
    // where it happened, and this will make sure we can get out of a bad state if we get into it.
    final ImmutableSet<JobId> curKeys = ImmutableSet.copyOf(this.items.keySet());
    for (final JobId key : curKeys) {
        if (this.items.get(key) == null) {
            this.items.remove(key);
        }
    }

    int itemCount = 0;
    for (final Deque<TaskStatusEvent> deque : items.values()) {
        itemCount += deque.size();
    }
    this.count = new AtomicInteger(itemCount);
}

From source file:interactivespaces.activity.component.ActivityComponentContextTest.java

/**
 * Make a couple of threads start running and see if they properly stop
 * running when the context signals startup successful.
 */// ww w  .  j  a v a2s. co m
@Test
public void testStartupWaitWithTwoThreadsSuccess() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(2);
    final CountDownLatch stopLatch = new CountDownLatch(2);
    final AtomicInteger countAllowedHandlers = new AtomicInteger(0);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            startLatch.countDown();

            if (context.canHandlerRun()) {
                countAllowedHandlers.incrementAndGet();
            }

            stopLatch.countDown();
        }
    };

    executor.execute(runnable);
    executor.execute(runnable);

    // Make sure they have both entered before starting the wait.
    Assert.assertTrue(startLatch.await(500, TimeUnit.MILLISECONDS));

    context.endStartupPhase(true);

    // Make sure they have both entered before starting the wait.
    Assert.assertTrue(stopLatch.await(500, TimeUnit.MILLISECONDS));

    // All handlers should have been allowed.
    Assert.assertEquals(2, countAllowedHandlers.get());
}

From source file:eu.itesla_project.modules.topo.PrintSubstationTopoHistoryTool.java

@Override
public void run(CommandLine line) throws Exception {
    String substationId = line.getOptionValue("substation-id");
    Interval interval = Interval.parse(line.getOptionValue("interval"));
    Path dictFile = null;//www  .  ja v a  2s  .co m
    if (line.hasOption("generate-short-ids-dict")) {
        dictFile = Paths.get(line.getOptionValue("generate-short-ids-dict"));
    }
    OfflineConfig config = OfflineConfig.load();
    Map<Set<TopoBus>, AtomicInteger> topos = new LinkedHashMap<>();
    try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) {
        int rowCount = histoDbClient.queryCount(interval, HistoDbHorizon.SN);
        Set<HistoDbAttributeId> attributeIds = Collections
                .singleton(new HistoDbNetworkAttributeId(substationId, HistoDbAttr.TOPO));
        try (InputStream is = histoDbClient.queryCsv(HistoQueryType.data, attributeIds, interval,
                HistoDbHorizon.SN, false, false)) {
            new TopoHistoryParser().parse(rowCount, is, new TopoHistoryHandler() {
                @Override
                public void onHeader(List<String> substationIds, int rowCount) {
                }

                @Override
                public void onTopology(int row, int col, Set<TopoBus> topo) {
                    if (topo != null) {
                        if (topos.containsKey(topo)) {
                            topos.get(topo).incrementAndGet();
                        } else {
                            topos.put(topo, new AtomicInteger(1));
                        }
                    }
                }
            });
        }
    }

    Map<Set<TopoBus>, AtomicInteger> topos2;
    if (dictFile != null) {
        ShortIdDictionary dict = createDict(topos.keySet());
        dict.write(dictFile);
        topos2 = translate(topos, dict);
    } else {
        topos2 = topos;
    }
    topos2.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}