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

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

Introduction

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

Prototype

public AtomicLong(long initialValue) 

Source Link

Document

Creates a new AtomicLong with the given initial value.

Usage

From source file:com.github.jackygurui.vertxredissonrepository.repository.SaveAndSearchAndGetCallInConcurrentTest.java

@Test
public void test2SaveAndSearchAndGetCallIn(TestContext context) throws Exception {
    Async async = context.async();/*  w  w  w  .j a v  a  2s .  com*/
    JsonNode source = JsonLoader.fromResource("/CallIn.json");
    int records = 1000;
    AtomicLong total = new AtomicLong(0);
    ConcurrentHashMap<JsonObject, String> m = new ConcurrentHashMap<>();
    Stream<JsonObject> stream = IntStream.rangeClosed(0, records).mapToObj(e -> {
        JsonObject clone = new JsonObject(Json.encode(source));
        Long number = Long.parseLong(clone.getString("phoneNumber")) + e;
        clone.put("phoneNumber", number + "");
        Long callTime = clone.getLong("callTime") + e;
        clone.put("callTime", callTime);
        return clone;
    });
    StopWatch sw = new StopWatch();
    sw.start();
    stream.parallel().forEach(e -> {
        org.simondean.vertx.async.Async.waterfall().<String>task(t -> {
            callInRepository.create(Json.encode(e), t);
        }).<List<CallIn>>task((id, t) -> {
            m.put(e, id);
            AtomicLong idc = new AtomicLong(0);
            org.simondean.vertx.async.Async.retry().<List<CallIn>>task(tt -> {
                callInRepository.searchIndexByScoreAndGet("callTime", e.getDouble("callTime"),
                        e.getDouble("callTime"), 0, 1, ttt -> {
                            logger.info("id = " + id + " | retry count: " + idc.incrementAndGet());
                            tt.handle(ttt.succeeded() && ttt.result() != null && !ttt.result().isEmpty()
                                    ? Future.succeededFuture(ttt.result())
                                    : Future.failedFuture(ttt.cause()));
                        });
            }).times(100000).run(t);
        }).run(r -> {
            context.assertTrue(r.succeeded());
            if (r.succeeded()) {
                context.assertFalse(r.result().isEmpty());
                context.assertEquals(1, r.result().size());
                CallIn ci = r.result().iterator().next();
                context.assertNotNull(ci);
                logger.info(Json.encode(ci));
                CallIn cii = Json.decodeValue(e.put("id", m.get(e)).encode(), CallIn.class);
                context.assertEquals(Json.encode(cii), Json.encode(ci));
            }
            long t;
            if ((t = total.incrementAndGet()) == records) {
                sw.stop();
                logger.info("time to concurrently save and search and get " + records + " call in records: "
                        + sw.getTime());
                async.complete();
            } else {
                logger.info("t = " + t);
            }
        });
    });

}

From source file:ch.algotrader.service.sim.SimulationOrderServiceImpl.java

public SimulationOrderServiceImpl(final OrderBook orderBook, final OrderExecutionService orderExecutionService,
        final MarketDataCacheService marketDataCacheService, final EngineManager engineManager) {

    Validate.notNull(orderBook, "OpenOrderRegistry is null");
    Validate.notNull(orderExecutionService, "OrderExecutionService is null");
    Validate.notNull(marketDataCacheService, "MarketDataCacheService is null");
    Validate.notNull(engineManager, "EngineManager is null");

    this.orderBook = orderBook;
    this.orderExecutionService = orderExecutionService;
    this.engineManager = engineManager;
    this.marketDataCacheService = marketDataCacheService;
    this.counter = new AtomicLong(0);
    this.seqnum = new AtomicLong(0);
}

From source file:com.streamsets.pipeline.stage.destination.datalake.writer.DataLakeDataGenerator.java

DataLakeDataGenerator(String filePath, OutputStreamHelper outputStreamHelper,
        DataGeneratorFormatConfig dataFormatConfig, long idleTimeSecs) throws IOException, StageException {
    this.filePath = filePath;
    this.outputStreamHelper = outputStreamHelper;
    this.cos = new CountingOutputStream(outputStreamHelper.getOutputStream(filePath));
    this.generator = dataFormatConfig.getDataGeneratorFactory().getGenerator(cos,
            outputStreamHelper.getStreamCloseEventHandler());
    this.idleTimeSecs = idleTimeSecs;
    this.recordCount = new AtomicLong(0L);
    this.idleClosed = false;
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.CounterConcurrentWaterfallTest.java

@Test
public void test5CounterConcurrentWaterfall(TestContext context) throws Exception {
    Async async = context.async();/* w ww  . java  2s  . co m*/
    HanyuPinyin.convert("");//warm up
    StopWatch sw = new StopWatch();
    sw.start();
    int records = 100;
    org.simondean.vertx.async.Async.<Long>series().task(customerRepository::totalCount).task(t -> {
        try {
            JsonNode source = JsonLoader.fromResource("/Customer.json");
            AtomicLong counter = new AtomicLong(0);
            IntStream.rangeClosed(1, records).parallel().forEach(e -> {
                JsonObject clone = new JsonObject(Json.encode(source));
                clone.getJsonObject("personalDetails").put("phoneNumber",
                        ((Long.parseLong(clone.getJsonObject("personalDetails").getString("phoneNumber"))
                                + 10000 + e) + ""));
                org.simondean.vertx.async.Async.waterfall().<String>task(tt -> {
                    customerRepository.create(Json.encode(clone), tt);
                }).<Customer>task((id, tt) -> {
                    customerRepository.get(id, tt);
                }).run((AsyncResult<Customer> r) -> {
                    long ct = counter.incrementAndGet();
                    //                logger.info("Counter = " + ct + " | success = " + !r.failed());
                    if (r.succeeded()) {
                        try {
                            Customer loaded = r.result();
                            Customer c = Json.decodeValue(clone.encode(), Customer.class);
                            c.setId(loaded.getId());
                            c.getAddressDetails().setId(loaded.getId());
                            c.getPersonalDetails().setId(loaded.getId());
                            String encoded = Json.encode(c);
                            if (!r.result().equals(encoded)) {
                                logger.info(loaded.getId() + " - SOURCE : " + encoded);
                                logger.info(loaded.getId() + " - RESULT : " + r.result());
                            }
                            context.assertEquals(Json.encode(r.result()), encoded);
                        } catch (Exception ex) {
                            t.handle(Future.failedFuture(ex));
                        }
                    } else {
                        t.handle(Future.failedFuture(r.cause()));
                    }
                    if (ct == records) {
                        t.handle(Future.succeededFuture(ct));
                    }
                });
            });
        } catch (IOException e) {
            t.handle(Future.failedFuture(e));
        }
    }).task(customerRepository::totalCount).run(r -> {
        if (r.succeeded()) {
            context.assertEquals(r.result().get(0) + r.result().get(1), r.result().get(2));
            sw.stop();
            logger.info("test count: time to count then concurrently save and get " + records
                    + " customer records and count again: " + sw.getTime());
            async.complete();
        } else {
            context.fail(r.cause());
            async.complete();
        }
    });
}

From source file:io.github.benas.jpopulator.impl.DefaultRandomizer.java

/**
 * Generate a random value for the given type.
 *
 * @param type the type for which a random value will be generated
 * @return a random value for the given type or null if the type is not supported
 *///from   w w w.ja v  a 2 s .  c om
public static Object getRandomValue(final Class type) {

    /*
     * String and Character types
     */
    if (type.equals(String.class)) {
        return RandomStringUtils.randomAlphabetic(ConstantsUtil.DEFAULT_STRING_LENGTH);
    }
    if (type.equals(Character.TYPE) || type.equals(Character.class)) {
        return RandomStringUtils.randomAlphabetic(1).charAt(0);
    }

    /*
     * Boolean type
     */
    if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
        return ConstantsUtil.RANDOM.nextBoolean();
    }

    /*
     * Numeric types
     */
    if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
        return (byte) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Short.TYPE) || type.equals(Short.class)) {
        return (short) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
        return ConstantsUtil.RANDOM.nextInt();
    }
    if (type.equals(Long.TYPE) || type.equals(Long.class)) {
        return ConstantsUtil.RANDOM.nextLong();
    }
    if (type.equals(Double.TYPE) || type.equals(Double.class)) {
        return ConstantsUtil.RANDOM.nextDouble();
    }
    if (type.equals(Float.TYPE) || type.equals(Float.class)) {
        return ConstantsUtil.RANDOM.nextFloat();
    }
    if (type.equals(BigInteger.class)) {
        return new BigInteger(
                Math.abs(ConstantsUtil.RANDOM.nextInt(ConstantsUtil.DEFAULT_BIG_INTEGER_NUM_BITS_LENGTH)),
                ConstantsUtil.RANDOM);
    }
    if (type.equals(BigDecimal.class)) {
        return new BigDecimal(ConstantsUtil.RANDOM.nextDouble());
    }
    if (type.equals(AtomicLong.class)) {
        return new AtomicLong(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(AtomicInteger.class)) {
        return new AtomicInteger(ConstantsUtil.RANDOM.nextInt());
    }

    /*
     * Date and time types
     */
    if (type.equals(java.util.Date.class)) {
        return ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue();
    }
    if (type.equals(java.sql.Date.class)) {
        return new java.sql.Date(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(java.sql.Time.class)) {
        return new java.sql.Time(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(java.sql.Timestamp.class)) {
        return new java.sql.Timestamp(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(Calendar.class)) {
        return Calendar.getInstance();
    }
    if (type.equals(org.joda.time.DateTime.class)) {
        return new org.joda.time.DateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDate.class)) {
        return new org.joda.time.LocalDate(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalTime.class)) {
        return new org.joda.time.LocalTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDateTime.class)) {
        return new org.joda.time.LocalDateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.Duration.class)) {
        return new org.joda.time.Duration(Math.abs(ConstantsUtil.RANDOM.nextLong()));
    }
    if (type.equals(org.joda.time.Period.class)) {
        return new org.joda.time.Period(Math.abs(ConstantsUtil.RANDOM.nextInt()));
    }
    if (type.equals(org.joda.time.Interval.class)) {
        long startDate = Math.abs(ConstantsUtil.RANDOM.nextInt());
        long endDate = startDate + Math.abs(ConstantsUtil.RANDOM.nextInt());
        return new org.joda.time.Interval(startDate, endDate);
    }

    /*
     * Enum type
     */
    if (type.isEnum() && type.getEnumConstants().length > 0) {
        Object[] enumConstants = type.getEnumConstants();
        return enumConstants[ConstantsUtil.RANDOM.nextInt(enumConstants.length)];
    }

    /*
     * Return null for any unsupported type
     */
    return null;

}

From source file:interactivespaces.time.NtpTimeProvider.java

/**
 * @param host/* ww w .  j  a va 2s .c  o  m*/
 *          the NTP host to use
 * @param updatePeriod
 *          how often the time should be updated from NTP
 * @param updatePeriodTimeUnit
 *          time units for the update period
 * @param scheduledExecutorService
 *          thread pool to use
 * @param log
 *          logger for the provider
 */
public NtpTimeProvider(InetAddress host, long updatePeriod, TimeUnit updatePeriodTimeUnit,
        ScheduledExecutorService scheduledExecutorService, Log log) {
    this.host = host;
    this.scheduledExecutorService = scheduledExecutorService;
    this.log = log;

    localTimeProvider = new LocalTimeProvider();
    ntpClient = new NTPUDPClient();
    offset = new AtomicLong(0);
    scheduledFuture = null;
}

From source file:com.taobao.tddl.interact.monitor.TotalStatMonitor.java

/**
 * virtual slot access counter//from   ww w  .j  a va  2  s.c o  m
 * 
 * @param key
 */
public static void virtualSlotIncrement(String key) {
    AtomicLong incre = virtualSlotMap.putIfAbsent(key, new AtomicLong(0));
    if (incre != null) {
        incre.addAndGet(1);
    }
}

From source file:jetbrains.exodus.entitystore.FileSystemBlobVaultOld.java

protected FileSystemBlobVaultOld(@NotNull final String parentDirectory, @NotNull final String blobsDirectory,
        @NotNull final String blobExtension, @NotNull final BlobHandleGenerator blobHandleGenerator,
        final int expectedVersion) throws IOException {
    this.blobsDirectory = blobsDirectory;
    this.blobExtension = blobExtension;
    location = new File(parentDirectory, blobsDirectory);
    this.blobHandleGenerator = blobHandleGenerator;
    size = new AtomicLong(UNKNOWN_SIZE);
    //noinspection ResultOfMethodCallIgnored
    location.mkdirs();/*from w  w  w. j a  v  a 2  s.com*/
    // load version
    final File versionFile = new File(location, VERSION_FILE);
    if (versionFile.exists()) {
        try (DataInputStream input = new DataInputStream(new FileInputStream(versionFile))) {
            version = input.readInt();
        }
        if (expectedVersion != version) {
            throw new UnexpectedBlobVaultVersionException("Unexpected FileSystemBlobVault version: " + version);
        }
    } else {
        final File[] files = location.listFiles();
        final boolean hasFiles = files != null && files.length > 0;
        if (!hasFiles) {
            version = expectedVersion;
        } else {
            version = EXPECTED_VERSION;
            if (expectedVersion != version) {
                throw new UnexpectedBlobVaultVersionException(
                        "Unexpected FileSystemBlobVault version: " + version);
            }
        }
        try (DataOutputStream output = new DataOutputStream(new FileOutputStream(versionFile))) {
            output.writeInt(expectedVersion);
        }
    }
}

From source file:com.netflix.spinnaker.kork.metrics.SpectatorMetricWriter.java

private AtomicLong getCounterStorage(Id id) {
    final AtomicLong newCounter = new AtomicLong(0);
    final AtomicLong existingCounter = counters.putIfAbsent(id, newCounter);
    if (existingCounter == null) {
        return newCounter;
    }//from  w  ww.j a v  a 2 s.co  m

    return existingCounter;
}

From source file:net.sourceforge.cobertura.metrics.model.coverage.CoverageRecord.java

/**
 * Compound constructor creating a CoverageRecord instance wrapping the supplied data.
 *
 * @param location The SourceLocation of this CoverageRecord.
 * @param hitCount The hitCount, i.e. the number of times that the supplied SourceLocation has been executed by
 *                 automated tests. Cannot be negative.
 *///ww  w . j ava 2  s .co  m
public CoverageRecord(final SourceLocation location, final long hitCount) {

    // Check santiy
    Validate.notNull(location, "Cannot handle null location argument.");
    Validate.isTrue(hitCount >= 0, "Cannot handle negative hitCount.");

    // Assign internal state
    this.location = location;
    this.hitCount = new AtomicLong(hitCount);
}