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

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

Introduction

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

Prototype

public final long get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.cloudera.oryx.app.traffic.TrafficUtil.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]");
        return;/*w w  w.j a  v a2  s .  c  o m*/
    }

    String[] hostStrings = COMMA.split(args[0]);
    Preconditions.checkArgument(hostStrings.length >= 1);
    int requestIntervalMS = Integer.parseInt(args[1]);
    Preconditions.checkArgument(requestIntervalMS >= 0);
    int numThreads = Integer.parseInt(args[2]);
    Preconditions.checkArgument(numThreads >= 1);

    String[] otherArgs = new String[args.length - 3];
    System.arraycopy(args, 3, otherArgs, 0, otherArgs.length);

    List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList());

    int perClientRequestIntervalMS = numThreads * requestIntervalMS;

    Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints());
    AtomicLong requestCount = new AtomicLong();
    AtomicLong serverErrorCount = new AtomicLong();
    AtomicLong clientErrorCount = new AtomicLong();
    AtomicLong exceptionCount = new AtomicLong();

    long start = System.currentTimeMillis();
    ExecUtils.doInParallel(numThreads, numThreads, true, i -> {
        RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
        ExponentialDistribution msBetweenRequests;
        if (perClientRequestIntervalMS > 0) {
            msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS);
        } else {
            msBetweenRequests = null;
        }

        ClientConfig clientConfig = new ClientConfig();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(numThreads);
        connectionManager.setDefaultMaxPerRoute(numThreads);
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        Client client = ClientBuilder.newClient(clientConfig);

        try {
            while (true) {
                try {
                    WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size())));
                    Endpoint endpoint = alsEndpoints.chooseEndpoint(random);
                    Invocation invocation = endpoint.makeInvocation(target, otherArgs, random);

                    long startTime = System.currentTimeMillis();
                    Response response = invocation.invoke();
                    try {
                        response.readEntity(String.class);
                    } finally {
                        response.close();
                    }
                    long elapsedMS = System.currentTimeMillis() - startTime;

                    int statusCode = response.getStatusInfo().getStatusCode();
                    if (statusCode >= 400) {
                        if (statusCode >= 500) {
                            serverErrorCount.incrementAndGet();
                        } else {
                            clientErrorCount.incrementAndGet();
                        }
                    }

                    endpoint.recordTiming(elapsedMS);

                    if (requestCount.incrementAndGet() % 10000 == 0) {
                        long elapsed = System.currentTimeMillis() - start;
                        log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)",
                                elapsed, requestCount.get(), clientErrorCount.get(), serverErrorCount.get(),
                                exceptionCount.get());
                        for (Endpoint e : alsEndpoints.getEndpoints()) {
                            log.info("{}", e);
                        }
                    }

                    if (msBetweenRequests != null) {
                        int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample());
                        if (elapsedMS < desiredElapsedMS) {
                            Thread.sleep(desiredElapsedMS - elapsedMS);
                        }
                    }
                } catch (Exception e) {
                    exceptionCount.incrementAndGet();
                    log.warn("{}", e.getMessage());
                }
            }
        } finally {
            client.close();
        }
    });
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

public static void main(String[] args) {

    String[] arguments = args[0].split(",");

    if (arguments.length < 1) {
        logErrorMessage("Unable to start stream : no arguments specified.", true);
        return;/*from  w w w.j  a v a  2s  . c  o  m*/
    }

    String videoFilePath = arguments[0];
    if (StringUtils.isBlank(videoFilePath)) {
        logErrorMessage("Unable to start stream : no video file path specified.", true);
        return;
    }

    String ip;
    int port;

    if (arguments.length == 1) {
        ip = DEFAULT_IP;
        port = DEFAULT_PORT;
        LOGGER.warn("No IP or port provided.  Using defaults : {}:{}", DEFAULT_IP, DEFAULT_PORT);
    } else if (arguments.length == 2) {
        ip = arguments[1];
        port = DEFAULT_PORT;
        LOGGER.warn("No port provided.  Using default : {}", DEFAULT_PORT);
    } else {
        ip = arguments[1];
        try {
            port = Integer.parseInt(arguments[2]);
        } catch (NumberFormatException e) {
            LOGGER.warn("Unable to parse specified port : {}.  Using Default : {}", arguments[2], DEFAULT_PORT);
            port = DEFAULT_PORT;
        }
    }

    LOGGER.info("Video file path : {}", videoFilePath);

    LOGGER.info("Streaming address : {}:{}", ip, port);

    final AtomicLong count = new AtomicLong(0);

    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                            DatagramPacket datagramPacket) throws Exception {
                        LOGGER.info("Reading datagram from channel");
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        logErrorMessage(String.format("Exception occured handling datagram packet.  %s", cause),
                                false);
                        ctx.close();
                    }
                });

        Channel ch = bootstrap.bind(0).sync().channel();

        File videoFile = new File(videoFilePath);

        long bytesSent = 0;

        long tsPacketCount = videoFile.length() / PACKET_SIZE;

        Duration videoDuration = getVideoDuration(videoFilePath);
        if (videoDuration == null) {
            return;
        }

        long tsDurationMillis = videoDuration.toMillis();

        LOGGER.info("Video Duration : {}", tsDurationMillis);

        double delayPerPacket = (double) tsDurationMillis / (double) tsPacketCount;

        long startTime = System.currentTimeMillis();

        int packetsSent = 0;

        try (final InputStream fis = new BufferedInputStream(new FileInputStream(videoFile))) {

            byte[] buffer = new byte[PACKET_SIZE];
            int c;
            while ((c = fis.read(buffer)) != -1) {
                bytesSent += c;

                ChannelFuture cf = ch.writeAndFlush(
                        new DatagramPacket(Unpooled.copiedBuffer(buffer), new InetSocketAddress(ip, port)));

                cf.await();

                packetsSent++;

                if (packetsSent % 100 == 0) {
                    Thread.sleep((long) (delayPerPacket * 100));
                }
                if (packetsSent % 10000 == 0) {
                    LOGGER.info("Packet sent : {}", packetsSent);
                }
            }
        }

        long endTime = System.currentTimeMillis();

        LOGGER.info("Time Elapsed: {}", endTime - startTime);

        if (!ch.closeFuture().await(100)) {
            logErrorMessage("Channel time out", false);
        }

        LOGGER.info("Bytes sent : {} ", bytesSent);

    } catch (InterruptedException | IOException e) {
        logErrorMessage(String.format("Unable to generate stream : %s", e), false);
    } finally {
        // Shut down the event loop to terminate all threads.
        eventLoopGroup.shutdownGracefully();
    }

    LOGGER.info("count = " + count.get());
}

From source file:com.btoddb.fastpersitentqueue.speedtest.SpeedTest.java

public static void main(String[] args) throws Exception {
    if (0 == args.length) {
        System.out.println();/*from w  ww  .  j  ava  2s  .c  o  m*/
        System.out.println("ERROR: must specify the config file path/name");
        System.out.println();
        System.exit(1);
    }

    SpeedTestConfig config = SpeedTestConfig.create(args[0]);

    System.out.println(config.toString());

    File theDir = new File(config.getDirectory(), "speed-" + UUID.randomUUID().toString());
    FileUtils.forceMkdir(theDir);

    Fpq queue = config.getFpq();
    queue.setJournalDirectory(new File(theDir, "journals"));
    queue.setPagingDirectory(new File(theDir, "pages"));

    try {
        queue.init();

        //
        // start workers
        //

        AtomicLong counter = new AtomicLong();
        AtomicLong pushSum = new AtomicLong();
        AtomicLong popSum = new AtomicLong();

        long startTime = System.currentTimeMillis();

        Set<SpeedPushWorker> pushWorkers = new HashSet<SpeedPushWorker>();
        for (int i = 0; i < config.getNumberOfPushers(); i++) {
            pushWorkers.add(new SpeedPushWorker(queue, config, counter, pushSum));
        }

        Set<SpeedPopWorker> popWorkers = new HashSet<SpeedPopWorker>();
        for (int i = 0; i < config.getNumberOfPoppers(); i++) {
            popWorkers.add(new SpeedPopWorker(queue, config, popSum));
        }

        ExecutorService pusherExecSrvc = Executors.newFixedThreadPool(
                config.getNumberOfPushers() + config.getNumberOfPoppers(), new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread t = new Thread(runnable);
                        t.setName("SpeedTest-Pusher");
                        return t;
                    }
                });

        ExecutorService popperExecSrvc = Executors.newFixedThreadPool(
                config.getNumberOfPushers() + config.getNumberOfPoppers(), new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread t = new Thread(runnable);
                        t.setName("SpeedTest-Popper");
                        return t;
                    }
                });

        long startPushing = System.currentTimeMillis();
        for (SpeedPushWorker sw : pushWorkers) {
            pusherExecSrvc.submit(sw);
        }

        long startPopping = System.currentTimeMillis();
        for (SpeedPopWorker sw : popWorkers) {
            popperExecSrvc.submit(sw);
        }

        //
        // wait to finish
        //

        long endTime = startTime + config.getDurationOfTest() * 1000;
        long endPushing = 0;
        long displayTimer = 0;
        while (0 == endPushing || !queue.isEmpty()) {
            // display status every second
            if (1000 < (System.currentTimeMillis() - displayTimer)) {
                System.out.println(String.format("status (%ds) : journals = %d : memory segments = %d",
                        (endTime - System.currentTimeMillis()) / 1000,
                        queue.getJournalMgr().getJournalIdMap().size(),
                        queue.getMemoryMgr().getSegments().size()));
                displayTimer = System.currentTimeMillis();
            }

            pusherExecSrvc.shutdown();
            if (pusherExecSrvc.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                endPushing = System.currentTimeMillis();
                // tell poppers, all pushers are finished
                for (SpeedPopWorker sw : popWorkers) {
                    sw.stopWhenQueueEmpty();
                }
            }
        }

        long endPopping = System.currentTimeMillis();

        popperExecSrvc.shutdown();
        popperExecSrvc.awaitTermination(10, TimeUnit.SECONDS);

        long numberOfPushes = 0;
        for (SpeedPushWorker sw : pushWorkers) {
            numberOfPushes += sw.getNumberOfEntries();
        }

        long numberOfPops = 0;
        for (SpeedPopWorker sw : popWorkers) {
            numberOfPops += sw.getNumberOfEntries();
        }

        long pushDuration = endPushing - startPushing;
        long popDuration = endPopping - startPopping;

        System.out.println("push - pop checksum = " + pushSum.get() + " - " + popSum.get() + " = "
                + (pushSum.get() - popSum.get()));
        System.out.println("push duration = " + pushDuration);
        System.out.println("pop duration = " + popDuration);
        System.out.println();
        System.out.println("pushed = " + numberOfPushes);
        System.out.println("popped = " + numberOfPops);
        System.out.println();
        System.out.println("push entries/sec = " + numberOfPushes / (pushDuration / 1000f));
        System.out.println("pop entries/sec = " + numberOfPops / (popDuration / 1000f));
        System.out.println();
        System.out.println("journals created = " + queue.getJournalsCreated());
        System.out.println("journals removed = " + queue.getJournalsRemoved());
    } finally {
        if (null != queue) {
            queue.shutdown();
        }
        //            FileUtils.deleteDirectory(theDir);
    }
}

From source file:Main.java

public static long getAndAddRequest(AtomicLong atomiclong, long l) {
    long l1;/*  w ww.  java 2s  . c o m*/
    do {
        l1 = atomiclong.get();
    } while (!atomiclong.compareAndSet(l1, addCap(l1, l)));
    return l1;
}

From source file:Main.java

/**
 * Atomically subtracts a value from the requested amount unless it's at Long.MAX_VALUE.
 * @param requested the requested amount holder
 * @param n the value to subtract from the requested amount, has to be positive (not verified)
 * @return the new requested amount//  w ww  . j av  a  2 s.  c  o m
 * @throws IllegalStateException if n is greater than the current requested amount, which
 * indicates a bug in the request accounting logic
 */
public static long produced(AtomicLong requested, long n) {
    for (;;) {
        long current = requested.get();
        if (current == Long.MAX_VALUE) {
            return Long.MAX_VALUE;
        }
        long next = current - n;
        if (next < 0L) {
            throw new IllegalStateException("More produced than requested: " + next);
        }
        if (requested.compareAndSet(current, next)) {
            return next;
        }
    }
}

From source file:Main.java

public static long getAndAddRequest(AtomicLong requested, long n) {
    long current;
    long next;/*from w  w w .  ja  v  a 2s .c om*/
    do {
        current = requested.get();
        next = current + n;
        if (next < 0) {
            next = Long.MAX_VALUE;
        }
    } while (!requested.compareAndSet(current, next));
    return current;
}

From source file:Main.java

static <T> long getAndAddRequest(AtomicLong paramAtomicLong, long paramLong) {
    long l1;/*from w  w w. ja v  a 2s  . c  om*/
    long l2;
    do {
        l1 = paramAtomicLong.get();
        l2 = l1 + paramLong;
        if (l2 < 0L)
            l2 = 9223372036854775807L;
    } while (!paramAtomicLong.compareAndSet(l1, l2));
    return l1;
}

From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java

public static void compareAndSetMax(final AtomicLong target, final long value) {
    long prev = target.get();
    while (value > prev) {
        boolean updated = target.compareAndSet(prev, value);
        if (updated)
            break;

        prev = target.get();//w w w .j a v a 2s .  co  m
    }
}

From source file:Main.java

/**
 * Adds {@code n} to {@code requested} and returns the value prior to addition once the
 * addition is successful (uses CAS semantics). If overflows then sets
 * {@code requested} field to {@code Long.MAX_VALUE}.
 * //from w w  w. j ava  2  s .co  m
 * @param requested
 *            atomic long that should be updated
 * @param n
 *            the number of requests to add to the requested count
 * @return requested value just prior to successful addition
 */
public static long getAndAddRequest(AtomicLong requested, long n) {
    // add n to field but check for overflow
    while (true) {
        long current = requested.get();
        long next = addCap(current, n);
        if (requested.compareAndSet(current, next)) {
            return current;
        }
    }
}

From source file:Main.java

private static Long fib(int n) throws InterruptedException {
    AtomicLong result = new AtomicLong();
    Phaser phaser = new Phaser();
    Task initialTask = new Task(n, result, phaser);
    phaser.register();/*from w ww  . j  a  va  2  s.  c  om*/
    executors.submit(initialTask);
    phaser.arriveAndAwaitAdvance();
    return result.get();
}