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:org.fcrepo.camel.processor.LdnProcessor.java

/**
 * Process the Fedora message//ww  w.  ja  v  a2 s .com
 *
 * @param exchange the current camel message exchange
 */
public void process(final Exchange exchange) throws IOException, NoSuchHeaderException {
    final Message in = exchange.getIn();
    final Model model = createDefaultModel();
    final Model newModel = createDefaultModel();
    final Resource resource = createResource(getSubjectUri(exchange));
    final Resource event = createResource("");
    final AtomicInteger counter = new AtomicInteger();
    final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();

    read(model, in.getBody(InputStream.class),
            contentTypeToLang(parse(in.getHeader(CONTENT_TYPE, String.class)).getMimeType()));

    newModel.add(createStatement(event, used, resource));
    model.listObjectsOfProperty(resource, wasGeneratedBy).forEachRemaining(obj -> {
        if (obj.isResource()) {
            obj.asResource().listProperties().forEachRemaining(stmt -> {
                newModel.add(createStatement(event, stmt.getPredicate(), stmt.getObject()));
            });
        }
    });
    model.listObjectsOfProperty(resource, wasAttributedTo).forEachRemaining(obj -> {
        final Resource agent = createResource("#agent" + Integer.toString(counter.getAndIncrement()));
        if (obj.isResource()) {
            obj.asResource().listProperties().forEachRemaining(stmt -> {
                newModel.add(createStatement(agent, stmt.getPredicate(), stmt.getObject()));
            });
        }
        newModel.add(createStatement(event, wasAssociatedWith, agent));
    });

    write(serializedGraph, newModel, JSONLD);
    in.setBody(serializedGraph.toString("UTF-8"));
    in.setHeader(HTTP_METHOD, "POST");
    in.setHeader(CONTENT_TYPE, "application/ld+json");
}

From source file:com.amazonaws.http.DelegatingDnsResolverTest.java

@Test
public void testDelegatingDnsResolverCallsResolveOnDelegate() throws Exception {
    final AtomicInteger timesCalled = new AtomicInteger();

    DnsResolver delegate = new DnsResolver() {
        @Override//  www .jav  a2  s.c  o  m
        public InetAddress[] resolve(String host) throws UnknownHostException {
            timesCalled.incrementAndGet();
            return new InetAddress[0];
        }
    };

    org.apache.http.conn.DnsResolver resolver = new DelegatingDnsResolver(delegate);

    resolver.resolve("localhost");

    assertEquals("Delegate Resolver should have been executed", 1, timesCalled.get());

}

From source file:com.vladmihalcea.OptimisticLockingTest.java

@Test
public void testRetries() throws InterruptedException {
    final Product product = productService.newProduct();
    assertEquals(0, product.getVersion());
    Product savedProduct = productService.updateName(product.getId(), "name");
    assertEquals(1, savedProduct.getVersion());

    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/*from ww  w .  j a v a 2 s  .  c om*/
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(product.getId(), 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:org.bitcoinrt.server.ConnectionBroker.java

@Override
public void onApplicationEvent(TcpConnectionEvent event) {

    final EventType eventType = event.getType();

    if (TcpConnectionEventType.OPEN.equals(eventType)) {

    } else if (TcpConnectionEventType.CLOSE.equals(eventType)) {
        logger.info("TCP Event: CLOSED - Removing client: {}", event.getConnectionId());
        clients.remove(event.getConnectionId());
    } else if (TcpConnectionEventType.EXCEPTION.equals(eventType)) {
        logger.warn("EXCEPTION Event - Removing client: {}", event.getConnectionId());
        clients.remove(event.getConnectionId());
    } else if (WebSocketEventType.HANDSHAKE_COMPLETE.equals(eventType)) {
        logger.info("HANDSHAKE_COMPLETE - Adding client: {}", event.getConnectionId());
        clients.put(event.getConnectionId(), new AtomicInteger());
    } else if (WebSocketEventType.WEBSOCKET_CLOSED.equals(eventType)) {
        logger.info("WEBSOCKET_CLOSED - Removing client: {}", event.getConnectionId());
        clients.remove(event.getConnectionId());
    } else {/*w  w  w  .jav  a 2s. co  m*/
        throw new IllegalArgumentException(String.format("EventType '%s' is not supported.", eventType));
    }
}

From source file:org.axonframework.migration.eventstore.JpaEventStoreMigrator.java

public boolean run() throws Exception {
    final AtomicInteger updateCount = new AtomicInteger();
    final AtomicInteger skipCount = new AtomicInteger();
    final AtomicLong lastId = new AtomicLong(
            Long.parseLong(configuration.getProperty("lastProcessedId", "-1")));
    try {//from  w  ww.java2 s .  c o  m
        TransactionTemplate template = new TransactionTemplate(txManager);
        template.setReadOnly(true);
        System.out.println("Starting conversion. Fetching batches of " + QUERY_BATCH_SIZE + " items.");
        while (template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                final Session hibernate = entityManager.unwrap(Session.class);
                Iterator<Object[]> results = hibernate.createQuery(
                        "SELECT e.aggregateIdentifier, e.sequenceNumber, e.type, e.id FROM DomainEventEntry e "
                                + "WHERE e.id > :lastIdentifier ORDER BY e.id ASC")
                        .setFetchSize(1000).setMaxResults(QUERY_BATCH_SIZE).setReadOnly(true)
                        .setParameter("lastIdentifier", lastId.get()).iterate();
                if (!results.hasNext()) {
                    System.out.println("Empty batch. Assuming we're done.");
                    return false;
                } else if (Thread.interrupted()) {
                    System.out.println("Received an interrupt. Stopping...");
                    return false;
                }
                while (results.hasNext()) {
                    List<ConversionItem> conversionBatch = new ArrayList<ConversionItem>();
                    while (conversionBatch.size() < CONVERSION_BATCH_SIZE && results.hasNext()) {
                        Object[] item = results.next();
                        String aggregateIdentifier = (String) item[0];
                        long sequenceNumber = (Long) item[1];
                        String type = (String) item[2];
                        Long entryId = (Long) item[3];
                        lastId.set(entryId);
                        conversionBatch
                                .add(new ConversionItem(sequenceNumber, aggregateIdentifier, type, entryId));
                    }
                    if (!conversionBatch.isEmpty()) {
                        executor.submit(new TransformationTask(conversionBatch, skipCount));
                    }
                }
                return true;
            }
        })) {
            System.out.println("Reading next batch, starting at ID " + lastId.get() + ".");
            System.out.println(
                    "Estimated backlog size is currently: " + (workQueue.size() * CONVERSION_BATCH_SIZE));
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.MINUTES);
        if (lastId.get() >= 0) {
            System.out.println(
                    "Processed events from old event store up to (and including) id = " + lastId.get());
        }
    }
    System.out.println("In total " + updateCount.get() + " items have been converted.");
    return skipCount.get() == 0;
}

From source file:net.sf.jasperreports.engine.fill.DelayedFillActions.java

private static int assignId(BaseReportFiller reportFiller) {
    AtomicInteger counter = (AtomicInteger) reportFiller.fillContext.getFillCache(FILL_CACHE_KEY_ID);
    if (counter == null) {
        // we just need a mutable integer, there's no actual concurrency here
        counter = new AtomicInteger();
        reportFiller.fillContext.setFillCache(FILL_CACHE_KEY_ID, counter);
    }//from  ww  w  .  j  av a2  s. co m

    return counter.incrementAndGet();
}

From source file:com.microsoft.wake.contrib.grouper.impl.AppendingSnowshovelGrouper.java

@Inject
public AppendingSnowshovelGrouper(Combiner<OutType, K, List<V>> c, Partitioner<K> p,
        Extractor<InType, K, V> ext,
        @Parameter(StageConfiguration.StageObserver.class) Observer<Tuple<Integer, OutType>> o,
        @Parameter(StageConfiguration.NumberOfThreads.class) int outputThreads,
        @Parameter(StageConfiguration.StageName.class) String stageName,
        @Parameter(ContinuousStage.PeriodNS.class) long outputPeriod_ns) {
    super(stageName);
    this.c = c;//w  w  w  .  j  av  a2  s  . c o m
    this.p = p;
    this.ext = ext;
    this.o = o;
    // calling this.new on a @Unit's inner class without its own state is currently the same as Tang injecting it
    this.outputDriver = new ContinuousStage<Object>(this.new OutputImpl(), outputThreads, stageName + "-out",
            outputPeriod_ns);
    this.doneHandler = ((ContinuousStage<Object>) outputDriver).getDoneHandler();
    register = new ConcurrentSkipListMap<>();
    inputDone = false;
    this.inputObserver = this.new InputImpl();

    this.sleeping = new AtomicInteger();

    // there is no dependence from input finish to output start
    // The alternative placement of this event is in the first call to onNext,
    // but Output onNext already provides blocking
    outputDriver.onNext(new GrouperEvent());
}

From source file:io.fabric8.example.test.msg.TestMsg.java

protected void doTest() throws Exception {

    //String msgURI = "tcp://" + getEnv("FABRIC8MQ_SERVICE_HOST", "localhost") + ":" + getEnv("FABRIC8MQ_SERVICE_PORT", "61616");
    String msgURI = Variables.MSG_URL;
    System.err.println("CONNECTING TO " + msgURI);
    PooledConnectionFactory connectionFactory = new PooledConnectionFactory();
    connectionFactory.setConnectionFactory(new ActiveMQConnectionFactory("failover:(" + msgURI + ")"));

    final AtomicInteger counter = new AtomicInteger();
    final CamelContext serviceContext = new DefaultCamelContext();
    serviceContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    serviceContext.addRoutes(new RouteBuilder() {
        @Override//from w  ww. j  av a 2  s  .  c o  m
        public void configure() throws Exception {
            RandomGenerator rg = new JDKRandomGenerator();
            int num = rg.nextInt();
            from("jms:topic:test").process(new Producer("FOO", serviceContext.createProducerTemplate()));

            from("jms:topic:test").process(new Producer("BAR", serviceContext.createProducerTemplate()));

            /*
            from("jms:queue:myQueue").process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                System.err.println("GOT A REPLY(" + exchange.getIn().getBody() + "!!! " + exchange.getIn().getHeaders());
            }
            });
            */

            from("jms:queue:myQueue").aggregate(header("CORRELATE"), new AggregationStrategy() {
                @Override
                public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
                    if (oldExchange == null) {
                        return newExchange;
                    }

                    String oldBody = oldExchange.getIn().getBody(String.class);
                    String newBody = newExchange.getIn().getBody(String.class);
                    oldExchange.getIn().setBody(oldBody + "+" + newBody);
                    return oldExchange;
                }
            }).completionSize(2).completionTimeout(2000).process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    System.err.println("YAY GOT RESULT " + exchange.getIn().getBody());
                }
            });
        }
    });
    serviceContext.start();

    CamelContext requestorContext = new DefaultCamelContext();
    requestorContext.addComponent("jms", ActiveMQComponent.jmsComponentAutoAcknowledge(connectionFactory));

    requestorContext.start();

    ProducerTemplate producerTemplate = requestorContext.createProducerTemplate();
    for (int i = 0; i < 1000; i++) {
        /*
        Object response = producerTemplate
                          .requestBodyAndHeader(
                                                   "jms:myQueue.queue?exchangePattern=InOut&requestTimeout=40000&timeToLive=40000"
                                                       + "&asyncConsumer=true&asyncStartListener=true&concurrentConsumers=10"
                                                       + "&useMessageIDAsCorrelationID=true",
                                                   "mBodyMsg", "HeaderString", "HeaderValue");
                
        System.err.println("RESPONSE = " + response);
        */
        String body = "TEST " + i;
        System.err.println("SENT MESSAGE " + body);
        String endPoint = "jms:topic:test?preserveMessageQos=true&replyTo=myQueue&replyToType=Exclusive"
                + "&asyncConsumer=true&asyncStartListener=true&concurrentConsumers=10";
        producerTemplate.sendBody(endPoint, body);
        Thread.sleep(1000);
    }

    requestorContext.stop();
    serviceContext.stop();
}

From source file:edu.uci.ics.hyracks.yarn.am.HyracksYarnApplicationMaster.java

private HyracksYarnApplicationMaster(Options options) {
    this.options = options;
    timer = new Timer(true);
    asks = new ArrayList<ResourceRequest>();
    resource2AskMap = new HashMap<Resource, Set<AskRecord>>();
    proc2AskMap = new HashMap<AbstractProcess, AskRecord>();
    lastResponseId = new AtomicInteger();

    String containerIdStr = System.getenv(ApplicationConstants.AM_CONTAINER_ID_ENV);
    ContainerId containerId = ConverterUtils.toContainerId(containerIdStr);
    appAttemptId = containerId.getApplicationAttemptId();
}

From source file:com.cyberway.issue.io.Warc2Arc.java

public void transform(final File warc, final File dir, final String prefix, final String suffix,
        final boolean force) throws IOException, java.text.ParseException {
    FileUtils.isReadable(warc);/*  w w  w .  j  a va2  s .c om*/
    FileUtils.isReadable(dir);
    WARCReader reader = WARCReaderFactory.get(warc);
    List<String> metadata = new ArrayList<String>();
    metadata.add("Made from " + reader.getReaderIdentifier() + " by " + this.getClass().getName() + "/"
            + getRevision());
    ARCWriter writer = new ARCWriter(new AtomicInteger(), Arrays.asList(new File[] { dir }), prefix, suffix,
            reader.isCompressed(), -1, metadata);
    transform(reader, writer);
}