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

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

Introduction

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

Prototype

public final void set(int newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.linkedin.pinot.tools.perf.QueryRunner.java

private static void reportAndClearStatistics(AtomicInteger numQueriesExecuted, AtomicLong totalBrokerTime,
        AtomicLong totalClientTime, List<Statistics> statisticsList) {
    numQueriesExecuted.set(0);
    totalBrokerTime.set(0L);/*from w  w  w  .ja v  a2 s . c o m*/
    totalClientTime.set(0L);
    for (Statistics statistics : statisticsList) {
        statistics.report();
        statistics.clear();
    }
}

From source file:fr.landel.utils.assertor.utils.AssertorIterable.java

private static <I extends Iterable<T>, T> boolean hasInOrder(final I iterable1, final Iterable<T> iterable2,
        final boolean not, final EnumAnalysisMode analysisMode) {

    long found = 0;
    final int size1 = IterableUtils.size(iterable1);
    final int size2 = IterableUtils.size(iterable2);

    if (size1 < size2) {
        return not;
    } else if (size1 == size2) {
        return not ^ iterable1.equals(iterable2);
    }//from ww w .j  av a 2  s .  c  o m

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        final Iterator<T> iterator1 = iterable1.iterator();
        Iterator<T> iterator2 = iterable2.iterator();

        // not empty pre-check, so we call next directly
        T value2 = iterator2.next();
        while (iterator1.hasNext() && found < size2) {
            if (Objects.equals(iterator1.next(), value2)) {
                ++found;
                if (iterator2.hasNext()) {
                    value2 = iterator2.next();
                }
            } else if (found > 0) {
                found = 0;
                iterator2 = iterable2.iterator();
                value2 = iterator2.next();
            }
        }
    } else {
        final AtomicInteger count = new AtomicInteger(0);

        final List<T> list2 = IterableUtils.toList(iterable2);

        StreamSupport.stream(iterable1.spliterator(), EnumAnalysisMode.PARALLEL.equals(analysisMode))
                .forEachOrdered(o -> {
                    int inc = count.get();
                    if (inc < size2) {
                        if (Objects.equals(o, list2.get(inc))) {
                            count.incrementAndGet();
                        } else if (inc > 0) {
                            count.set(0);
                        }
                    }
                });

        found = count.get();
    }

    return not ^ (found == size2);
}

From source file:net.nfpj.webcounter.dm.MemCounterDM.java

@Override
public Counter reset(String name) throws IllegalArgumentException {
    if (name == null || name.isEmpty()) {
        throw new NullPointerException("Name cannot be null");
    }/*from ww w  . ja  v  a2s.co  m*/
    AtomicInteger ai = counters.get(name);
    if (ai != null) {
        ai.set(0);
        return new Counter(name, 0);
    } else {
        return null;
    }
}

From source file:org.apache.hadoop.fs.FCStatisticsBaseTest.java

@Test(timeout = 70000)
public void testStatisticsThreadLocalDataCleanUp() throws Exception {
    final Statistics stats = new Statistics("test");
    // create a small thread pool to test the statistics
    final int size = 2;
    ExecutorService es = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(size);
    for (int i = 0; i < size; i++) {
        tasks.add(new Callable<Boolean>() {
            public Boolean call() {
                // this populates the data set in statistics
                stats.incrementReadOps(1);
                return true;
            }//from   w ww  . jav a 2  s.com
        });
    }
    // run the threads
    es.invokeAll(tasks);
    // assert that the data size is exactly the number of threads
    final AtomicInteger allDataSize = new AtomicInteger(0);
    allDataSize.set(stats.getAllThreadLocalDataSize());
    Assert.assertEquals(size, allDataSize.get());
    Assert.assertEquals(size, stats.getReadOps());
    // force the GC to collect the threads by shutting down the thread pool
    es.shutdownNow();
    es.awaitTermination(1, TimeUnit.MINUTES);
    es = null;
    System.gc(); // force GC to garbage collect threads

    // wait for up to 60 seconds
    GenericTestUtils.waitFor(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            int size = stats.getAllThreadLocalDataSize();
            allDataSize.set(size);
            if (size == 0) {
                return true;
            }
            LOG.warn(
                    "not all references have been cleaned up; still " + allDataSize.get() + " references left");
            LOG.warn("triggering another GC");
            System.gc();
            return false;
        }
    }, 500, 60 * 1000);
    Assert.assertEquals(0, allDataSize.get());
    Assert.assertEquals(size, stats.getReadOps());
}

From source file:org.hyperic.hq.bizapp.server.session.HQInternalService.java

public int getAgentCount() {
    final ClassLoader cl = agentManager.getClass().getClassLoader();
    final AtomicInteger atInt = new AtomicInteger(-1);
    final AgentManager aMan = agentManager;
    final Runnable runner = new Runnable() {

        public void run() {
            atInt.set(aMan.getAgentCountUsed());
        }//from w  w  w  . j  a  v  a 2s . com
    };
    runInContext(runner, cl);
    return atInt.get();
}

From source file:org.hyperic.hq.bizapp.server.session.HQInternalService.java

public int getPlatformCount() {
    final ClassLoader cl = agentManager.getClass().getClassLoader();
    final AtomicInteger atInt = new AtomicInteger(-1);
    final PlatformManager pMan = platformManager;
    final Runnable runner = new Runnable() {
        public void run() {
            atInt.set(pMan.getPlatformCount().intValue());
        }/*from   w w w. ja  v  a 2  s .c om*/
    };
    runInContext(runner, cl);
    return atInt.get();
}

From source file:cf.spring.servicebroker.ServiceBrokerTest.java

private void doProvisionTest(ProvisionBody provisionBody) throws IOException {
    final AtomicInteger provisionCounter = context.getBean("provisionCounter", AtomicInteger.class);
    provisionCounter.set(0);

    // Do provision
    final HttpUriRequest provisionRequest = RequestBuilder.put().setUri(instanceUri)
            .setEntity(new StringEntity(mapper.writeValueAsString(provisionBody), ContentType.APPLICATION_JSON))
            .build();/*from w  w w. j a va2s. c om*/
    final CloseableHttpResponse provisionResponse = client.execute(provisionRequest);
    assertEquals(provisionResponse.getStatusLine().getStatusCode(), 201);
    assertEquals(provisionCounter.get(), 1);

    final JsonNode provisionResponseJson = mapper.readTree(provisionResponse.getEntity().getContent());
    assertTrue(provisionResponseJson.has("dashboard_url"));
    assertEquals(provisionResponseJson.get("dashboard_url").asText(), DASHBOARD_URL);
}

From source file:org.apache.hama.monitor.TestFederator.java

public void testExecutionFlow() throws Exception {
    LOG.info("Value before submitted: " + expected);
    final AtomicInteger finalResult = new AtomicInteger(0);
    final Act act = new Act(new DummyCollector(expected), new CollectorHandler() {
        @Override//from  w  ww.jav  a  2s.  com
        public void handle(@SuppressWarnings("rawtypes") Future future) {
            try {
                finalResult.set(((Integer) future.get()).intValue());
                LOG.info("Value after submitted: " + finalResult);
            } catch (ExecutionException ee) {
                LOG.error(ee);
            } catch (InterruptedException ie) {
                LOG.error(ie);
                Thread.currentThread().interrupt();
            }
        }
    });
    this.federator.register(act);
    Thread.sleep(3 * 1000);
    assertEquals("Result should be " + (expected + 1) + ".", finalResult.get(), (expected + 1));
}

From source file:org.spout.engine.filesystem.WorldFiles.java

public static void readColumn(InputStream in, SpoutColumn column, AtomicInteger lowestY,
        BlockMaterial[][] topmostBlocks) {
    if (in == null) {
        //The inputstream is null because no height map data exists
        for (int x = 0; x < SpoutColumn.BLOCKS.SIZE; x++) {
            for (int z = 0; z < SpoutColumn.BLOCKS.SIZE; z++) {
                column.getAtomicInteger(x, z).set(Integer.MIN_VALUE);
                topmostBlocks[x][z] = null;
                column.setDirty(x, z);//from   w w w.  ja  v  a2s . c  o m
            }
        }
        lowestY.set(Integer.MAX_VALUE);
        return;
    }

    DataInputStream dataStream = new DataInputStream(in);
    try {
        for (int x = 0; x < SpoutColumn.BLOCKS.SIZE; x++) {
            for (int z = 0; z < SpoutColumn.BLOCKS.SIZE; z++) {
                column.getAtomicInteger(x, z).set(dataStream.readInt());
            }
        }
        @SuppressWarnings("unused")
        int version = dataStream.readInt();

        lowestY.set(dataStream.readInt());

        //Save heightmap
        StringMap global = ((SpoutEngine) Spout.getEngine()).getEngineItemMap();
        StringMap itemMap = column.getWorld().getItemMap();
        boolean warning = false;
        for (int x = 0; x < SpoutColumn.BLOCKS.SIZE; x++) {
            for (int z = 0; z < SpoutColumn.BLOCKS.SIZE; z++) {
                if (!dataStream.readBoolean()) {
                    continue;
                }
                int blockState = dataStream.readInt();
                short blockId = BlockFullState.getId(blockState);
                short blockData = BlockFullState.getData(blockState);
                blockId = (short) itemMap.convertTo(global, blockId);
                blockState = BlockFullState.getPacked(blockId, blockData);
                BlockMaterial m;
                try {
                    m = (BlockMaterial) MaterialRegistry.get(blockState);
                } catch (ClassCastException e) {
                    m = null;
                    if (!warning) {
                        Spout.getLogger().severe(
                                "Error reading column topmost block information, block was not a valid BlockMaterial");
                        warning = false;
                    }
                }
                if (m == null) {
                    column.setDirty(x, z);
                }
                topmostBlocks[x][z] = m;
            }
        }

        //Save Biomes
        BiomeManager manager = null;
        try {
            //Biome manager is serialized with:
            // - boolean, if a biome manager exists
            // - String, the class name
            // - int, the number of bytes of data to read
            // - byte[], size of the above int in length
            boolean exists = dataStream.readBoolean();
            if (exists) {
                String biomeManagerClass = dataStream.readUTF();
                int biomeSize = dataStream.readInt();
                byte[] biomes = new byte[biomeSize];
                dataStream.readFully(biomes);

                //Attempt to create the biome manager class from the class name
                @SuppressWarnings("unchecked")
                Class<? extends BiomeManager> clazz = (Class<? extends BiomeManager>) Class
                        .forName(biomeManagerClass);
                Class<?>[] params = { int.class, int.class };
                manager = clazz.getConstructor(params).newInstance(column.getX(), column.getZ());
                manager.deserialize(biomes);
                column.setBiomeManager(manager);
            }
        } catch (Exception e) {
            Spout.getLogger().log(Level.SEVERE, "Failed to read biome data for column", e);
        }

    } catch (IOException e) {
        Spout.getLogger()
                .severe("Error reading column height-map for column" + column.getX() + ", " + column.getZ());
    }
}

From source file:org.b3log.latke.ioc.JavassistMethodHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Method proceed, final Object[] params)
        throws Throwable {
    LOGGER.trace("Processing invocation [" + method.toString() + "]");

    AtomicInteger calls = CALLS.get();
    if (null == calls) {
        synchronized (this) {
            if (null == calls) {
                calls = new AtomicInteger(0);
                CALLS.set(calls);
            }/*w w  w  . j a v a  2s.c om*/
        }
    }
    calls.incrementAndGet();

    // Invocation with transaction handle
    final boolean withTransactionalAnno = method.isAnnotationPresent(Transactional.class);
    JdbcTransaction transaction = JdbcRepository.TX.get();
    final boolean alreadyInTransaction = null != transaction;
    final boolean needHandleTrans = withTransactionalAnno && !alreadyInTransaction;

    // Transaction Propagation: REQUIRED (Support a current transaction, create a new one if none exists)
    if (needHandleTrans) {
        try {
            transaction = new JdbcTransaction();
        } catch (final SQLException e) {
            LOGGER.log(Level.ERROR, "Failed to initialize JDBC transaction", e);

            throw new IllegalStateException("Begin a transaction failed");
        }

        JdbcRepository.TX.set(transaction);
    }

    Object ret;
    try {
        ret = proceed.invoke(proxy, params);

        if (needHandleTrans) {
            transaction.commit();
        }
    } catch (final InvocationTargetException e) {
        if (needHandleTrans) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }

        throw e.getTargetException();
    }

    if (0 == calls.decrementAndGet()) {
        CALLS.set(null);
        final Connection connection = JdbcRepository.CONN.get();
        if (null != connection) {
            connection.close();
            JdbcRepository.CONN.set(null);
        }
    }

    return ret;
}