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

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

Introduction

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

Prototype

public final int incrementAndGet() 

Source Link

Document

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

Usage

From source file:com.zaubersoftware.gnip4j.api.impl.XMLActivityStreamFeedProcessorTest.java

/** test */
@Test/*from ww w  .ja va 2s.c om*/
public final void test() throws IOException, ParseException {
    final InputStream is = getClass().getResourceAsStream("fanpage.xml");
    try {
        final AtomicInteger i = new AtomicInteger();
        final ObjectMapper mapper = JsonActivityFeedProcessor.getObjectMapper();
        final FeedProcessor p = new XMLActivityStreamFeedProcessor<Activity>("foo", new DirectExecuteService(),
                new StreamNotificationAdapter<Activity>() {
                    @Override
                    public void notify(final Activity activity, final GnipStream stream) {
                        i.incrementAndGet();
                        try {
                            final byte[] data0 = mapper.writeValueAsBytes(activity);
                            final Activity e = mapper.reader(Activity.class).readValue(data0);
                            final byte[] data1 = mapper.writeValueAsBytes(e);
                            assertArrayEquals(data0, data1);

                            // test serialization
                            final ObjectOutputStream os = new ObjectOutputStream(new ByteArrayOutputStream());
                            os.writeObject(activity);
                            os.close();
                        } catch (final Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }, new ActivityUnmarshaller("hola"));
        p.process(is);
        assertEquals(23, i.get());
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.cloudera.lib.service.instrumentation.TestInstrumentationService.java

@Test
@TestDir/* w ww  .ja  v  a 2s .c om*/
@SuppressWarnings("unchecked")
public void sampling() throws Exception {
    String dir = getTestDir().getAbsolutePath();
    String services = StringUtils.toString(
            Arrays.asList(InstrumentationService.class.getName(), SchedulerService.class.getName()), ",");
    XConfiguration conf = new XConfiguration();
    conf.set("server.services", services);
    Server server = new Server("server", dir, dir, dir, dir, conf);
    server.init();
    Instrumentation instrumentation = server.get(Instrumentation.class);

    final AtomicInteger count = new AtomicInteger();

    Instrumentation.Variable<Long> varToSample = new Instrumentation.Variable<Long>() {
        @Override
        public Long getValue() {
            return (long) count.incrementAndGet();
        }
    };
    instrumentation.addSampler("g", "s", 10, varToSample);

    sleep(2000);
    int i = count.get();
    Assert.assertTrue(i > 0);

    Map<String, Map<String, ?>> snapshot = instrumentation.getSnapshot();
    Map<String, Map<String, Object>> samplers = (Map<String, Map<String, Object>>) snapshot.get("samplers");
    InstrumentationService.Sampler sampler = (InstrumentationService.Sampler) samplers.get("g").get("s");
    Assert.assertTrue(sampler.getRate() > 0);

    server.destroy();
}

From source file:com.asakusafw.lang.compiler.cli.BatchCompilerCliTest.java

/**
 * full args./*  ww  w .j a  v a 2 s . c o  m*/
 * @throws Exception if failed
 */
@Test
public void execute_full() throws Exception {
    File output = deployer.newFolder();
    File explore = prepareLibrary("explore");
    File external = prepareLibrary("external");
    File embed = prepareLibrary("embed");
    File attach = prepareLibrary("attach");
    String[] args = strings(new Object[] { "--explore",
            files(ResourceUtil.findLibraryByClass(DummyBatch.class), explore), "--output", output,
            "--classAnalyzer", classes(DummyClassAnalyzer.class), "--batchCompiler",
            classes(DelegateBatchCompiler.class), "--external", files(external), "--embed", files(embed),
            "--attach", files(attach), "--include", classes(DummyBatch.class), "--dataModelProcessors",
            classes(DummyDataModelProcessor.class), "--externalPortProcessors",
            classes(DummyExternalPortProcessor.class), "--batchProcessors", classes(DummyBatchProcessor.class),
            "--jobflowProcessors", classes(DummyJobflowProcessor.class), "--participants",
            classes(DummyCompilerParticipant.class), "--runtimeWorkingDirectory", "testRuntimeWorkingDirectory",
            "--failOnError", true, "--batchIdPrefix", "prefix.", "-P", "a=b", "-property", "c=d", });
    AtomicInteger count = new AtomicInteger();
    int status = execute(args, (context, batch) -> {
        count.incrementAndGet();
        assertThat(batch.getBatchId(), is("prefix.DummyBatch"));
        assertThat(batch.getDescriptionClass(), is(classOf(DummyBatch.class)));
        assertThat(context.getOutput().getBasePath(), is(new File(output, batch.getBatchId())));

        assertThat(context.getProject().getClassLoader().getResource("explore"), is(notNullValue()));
        assertThat(context.getProject().getClassLoader().getResource("embed"), is(notNullValue()));
        assertThat(context.getProject().getClassLoader().getResource("attach"), is(notNullValue()));
        assertThat(context.getProject().getClassLoader().getResource("external"), is(notNullValue()));

        assertThat(context.getProject().getProjectContents(), includes("explore"));
        assertThat(context.getProject().getProjectContents(), not(includes("embed")));
        assertThat(context.getProject().getProjectContents(), not(includes("attach")));
        assertThat(context.getProject().getProjectContents(), not(includes("external")));

        // --explore -> implicitly embedded
        assertThat(context.getProject().getEmbeddedContents(), includes("explore"));
        assertThat(context.getProject().getEmbeddedContents(), includes("embed"));
        assertThat(context.getProject().getEmbeddedContents(), not(includes("attach")));
        assertThat(context.getProject().getEmbeddedContents(), not(includes("external")));

        assertThat(context.getProject().getAttachedLibraries(), not(deepIncludes("explore")));
        assertThat(context.getProject().getAttachedLibraries(), not(deepIncludes("embed")));
        assertThat(context.getProject().getAttachedLibraries(), deepIncludes("attach"));
        assertThat(context.getProject().getAttachedLibraries(), not(deepIncludes("external")));

        assertThat(context.getTools().getDataModelProcessor(), is(consistsOf(DummyDataModelProcessor.class)));
        assertThat(context.getTools().getExternalPortProcessor(),
                is(consistsOf(DummyExternalPortProcessor.class)));
        assertThat(context.getTools().getBatchProcessor(), is(consistsOf(DummyBatchProcessor.class)));
        assertThat(context.getTools().getJobflowProcessor(), is(consistsOf(DummyJobflowProcessor.class)));
        assertThat(context.getTools().getParticipant(), is(consistsOf(DummyCompilerParticipant.class)));
    });
    assertThat(status, is(0));
    assertThat(count.get(), is(1));
}

From source file:com.ning.arecibo.collector.persistent.TestDefaultTimelineDAO.java

@Test(groups = "slow")
public void testGetSampleKindsByHostName() throws Exception {
    final TimelineDAO dao = new DefaultTimelineDAO(helper.getDBI(), sampleCoder);
    final DateTime startTime = new DateTime(DateTimeZone.UTC);
    final DateTime endTime = startTime.plusSeconds(2);

    // Create the host
    final String hostName = UUID.randomUUID().toString();
    final Integer hostId = dao.getOrAddHost(hostName);
    Assert.assertNotNull(hostId);/*from ww  w. j ava  2  s. c  o m*/

    // Create a timeline times (needed for the join in the dashboard query)
    final Integer eventCategoryId = 123;

    // Create the samples
    final String sampleOne = UUID.randomUUID().toString();
    final Integer sampleOneId = dao.getOrAddSampleKind(hostId, eventCategoryId, sampleOne);
    Assert.assertNotNull(sampleOneId);
    final String sampleTwo = UUID.randomUUID().toString();
    final Integer sampleTwoId = dao.getOrAddSampleKind(hostId, eventCategoryId, sampleTwo);
    Assert.assertNotNull(sampleTwoId);

    // Basic retrieval tests
    final BiMap<Integer, CategoryIdAndSampleKind> sampleKinds = dao.getSampleKinds();
    Assert.assertEquals(sampleKinds.size(), 2);
    Assert.assertEquals(sampleKinds.get(sampleOneId).getEventCategoryId(), (int) eventCategoryId);
    Assert.assertEquals(sampleKinds.get(sampleOneId).getSampleKind(), sampleOne);
    Assert.assertEquals(sampleKinds.get(sampleTwoId).getEventCategoryId(), (int) eventCategoryId);
    Assert.assertEquals(sampleKinds.get(sampleTwoId).getSampleKind(), sampleTwo);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleOneId).getEventCategoryId(),
            (int) eventCategoryId);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleOneId).getSampleKind(), sampleOne);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleTwoId).getEventCategoryId(),
            (int) eventCategoryId);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleTwoId).getSampleKind(), sampleTwo);

    // No samples yet
    Assert.assertEquals(ImmutableList.<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId)).size(), 0);

    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, hostId, sampleOneId, startTime, endTime,
            new byte[0], new byte[0], 0));
    final ImmutableList<Integer> firstFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(firstFetch.size(), 1);
    Assert.assertEquals(firstFetch.get(0), sampleOneId);

    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, hostId, sampleTwoId, startTime, endTime,
            new byte[0], new byte[0], 0));
    final ImmutableList<Integer> secondFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(secondFetch.size(), 2);
    Assert.assertTrue(secondFetch.contains(sampleOneId));
    Assert.assertTrue(secondFetch.contains(sampleTwoId));

    // Random sampleKind for random host
    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, Integer.MAX_VALUE - 100, Integer.MAX_VALUE,
            startTime, endTime, new byte[0], new byte[0], 0));
    final ImmutableList<Integer> thirdFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(secondFetch.size(), 2);
    Assert.assertTrue(thirdFetch.contains(sampleOneId));
    Assert.assertTrue(thirdFetch.contains(sampleTwoId));

    // Test dashboard query
    final AtomicInteger chunksSeen = new AtomicInteger(0);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(sampleOneId, sampleTwoId), startTime, startTime.plusSeconds(2),
            new TimelineChunkConsumer() {
                @Override
                public void processTimelineChunk(final TimelineChunk chunk) {
                    chunksSeen.incrementAndGet();
                    Assert.assertEquals((Integer) chunk.getHostId(), hostId);
                    Assert.assertTrue(
                            chunk.getSampleKindId() == sampleOneId || chunk.getSampleKindId() == sampleTwoId);
                }
            });
    Assert.assertEquals(chunksSeen.get(), 2);

    // Dummy queries
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(Integer.MAX_VALUE), null, startTime,
            startTime.plusDays(1), FAIL_CONSUMER);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(Integer.MAX_VALUE), startTime, startTime.plusDays(1), FAIL_CONSUMER);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(sampleOneId, sampleTwoId), startTime.plusDays(1), startTime.plusDays(2),
            FAIL_CONSUMER);
}

From source file:org.apache.blur.shell.QueryCommand.java

private void count(Record record, AtomicInteger recordCount, AtomicInteger columnCount,
        AtomicInteger columnSize) {
    recordCount.incrementAndGet();
    List<Column> columns = record.getColumns();
    if (columns != null) {
        for (Column column : columns) {
            count(column, columnCount, columnSize);
        }/*from   w w  w.  j av  a2s  . c om*/
    }
}

From source file:com.netflix.spinnaker.front50.migrations.LinearToParallelMigration.java

private void migrate(ItemDAO<Pipeline> dao, String type, Pipeline pipeline) {
    log.info(format("Migrating %s '%s' from linear -> parallel", type, pipeline.getId()));

    AtomicInteger refId = new AtomicInteger(0);
    List<Map<String, Object>> stages = (List<Map<String, Object>>) pipeline.getOrDefault("stages",
            Collections.emptyList());
    stages.forEach(stage -> {//from w  w  w  .j  a v  a  2  s .c  om
        stage.put("refId", String.valueOf(refId.get()));
        if (refId.get() > 0) {
            stage.put("requisiteStageRefIds", Collections.singletonList(String.valueOf(refId.get() - 1)));
        } else {
            stage.put("requisiteStageRefIds", Collections.emptyList());
        }

        refId.incrementAndGet();
    });

    pipeline.put("parallel", true);
    dao.update(pipeline.getId(), pipeline);

    log.info(format("Migrated %s '%s' from linear -> parallel", type, pipeline.getId()));
}

From source file:com.cyngn.vertx.bosun.BosunReporterTests.java

@Test
public void testSendMany(TestContext context) throws Exception {
    JsonObject metric = new JsonObject();
    metric.put("action", BosunReporter.INDEX_COMMAND);
    metric.put("metric", "test.value");
    metric.put("value", "34.4");
    metric.put("tags", new JsonObject().put("foo", "bar"));

    int totalMessages = 10000;
    AtomicInteger count = new AtomicInteger(0);
    Async async = context.async();/*  www .  j  ava2  s .  c  o m*/

    AtomicInteger okCount = new AtomicInteger(0);

    Handler<AsyncResult<Message<JsonObject>>> handler = result -> {
        if (result.failed()) {
            context.fail();
        }

        String response = result.result().body().getString(BosunReporter.RESULT_FIELD);
        if (StringUtils.equals(BosunResponse.OK_MSG, response)) {
            okCount.incrementAndGet();
        } else if (StringUtils.equals(BosunResponse.EXISTS_MSG, response)) {
        } else {
            context.fail();
        }

        if (count.incrementAndGet() == totalMessages) {
            if (okCount.get() != 1) {
                context.fail();
                return;
            }
            async.complete();
        }
    };

    for (int i = 0; i < totalMessages; i++) {
        eb.send(topic, metric, new DeliveryOptions(), handler);
    }
}

From source file:de.bund.bfr.math.MultivariateOptimization.java

@Override
public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful,
        Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations,
        DoubleConsumer progessListener, ExecutionContext exec) throws CanceledExecutionException {
    if (exec != null) {
        exec.checkCanceled();/*from   www  .  jav  a  2  s  .c o m*/
    }

    progessListener.accept(0.0);

    List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues,
            nParameterSpace);

    ranges.set(parameters.indexOf(sdParam), new ParamRange(1.0, 1, 1.0));

    List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations,
            values -> optimizerFunction.value(Doubles.toArray(values)),
            progress -> progessListener.accept(0.5 * progress), exec);
    Result result = new Result();
    AtomicInteger currentIteration = new AtomicInteger();
    SimplexOptimizer optimizer = new SimplexOptimizer(new SimpleValueChecker(1e-10, 1e-10) {

        @Override
        public boolean converged(int iteration, PointValuePair previous, PointValuePair current) {
            if (super.converged(iteration, previous, current)) {
                return true;
            }

            return currentIteration.incrementAndGet() >= maxIterations;
        }
    });
    int count = 0;

    for (StartValues startValues : startValuesList) {
        if (exec != null) {
            exec.checkCanceled();
        }

        progessListener.accept(0.5 * count++ / startValuesList.size() + 0.5);

        try {
            PointValuePair optimizerResults = optimizer.optimize(new MaxEval(Integer.MAX_VALUE),
                    new MaxIter(maxIterations), new InitialGuess(Doubles.toArray(startValues.getValues())),
                    new ObjectiveFunction(optimizerFunction), GoalType.MAXIMIZE,
                    new NelderMeadSimplex(parameters.size()));
            double logLikelihood = optimizerResults.getValue() != null ? optimizerResults.getValue()
                    : Double.NaN;

            if (result.logLikelihood == null || logLikelihood > result.logLikelihood) {
                result = getResults(optimizerResults);

                if (result.logLikelihood == 0.0 || stopWhenSuccessful) {
                    break;
                }
            }
        } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) {
        }
    }

    return result;
}

From source file:io.fabric8.msg.jnatsd.TestProtocol.java

@Test
public void testSendAndRecv() throws Exception {
    try (Connection c = connectionFactory.createConnection()) {
        assertFalse(c.isClosed());//from  w  w  w  . ja  v  a2 s.com
        final AtomicInteger received = new AtomicInteger();
        int count = 1000;
        try (AsyncSubscription s = c.subscribeAsync("foo", new MessageHandler() {
            public void onMessage(Message msg) {
                received.incrementAndGet();
            }
        })) {
            // s.start();
            assertFalse(c.isClosed());
            for (int i = 0; i < count; i++) {
                c.publish("foo", null);
            }
            c.flush();

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            assertTrue(String.format("Received (%s) != count (%s)", received, count), received.get() == count);
        }
    }
}

From source file:org.jtheque.core.CoreTest.java

@Test
@DirtiesContext//  w  w w.  ja  v a2s .  c  o m
public void applicationListener() {
    final AtomicInteger counter = new AtomicInteger(0);

    final Application launchedApplication = new TestApplication();

    core.addApplicationListener(new ApplicationListener() {
        @Override
        public void applicationLaunched(Application application) {
            assertEquals(application, launchedApplication);
            assertEquals(application, core.getApplication());

            counter.incrementAndGet();
        }
    });

    core.launchApplication(launchedApplication);

    assertEquals(1, counter.intValue());
}