List of usage examples for java.util.concurrent.atomic AtomicInteger incrementAndGet
public final int incrementAndGet()
From source file:org.apache.hadoop.hbase.util.FSRegionScanner.java
@Override public void run() { try {// www . j a v a 2 s. c o m // empty the map for each region Map<String, AtomicInteger> blockCountMap = new HashMap<String, AtomicInteger>(); //get table name String tableName = regionPath.getParent().getName(); int totalBlkCount = 0; // ignore null FileStatus[] cfList = fs.listStatus(regionPath); if (null == cfList) { return; } // for each cf, get all the blocks information for (FileStatus cfStatus : cfList) { if (!cfStatus.isDirectory()) { // skip because this is not a CF directory continue; } if (cfStatus.getPath().getName().startsWith(".") || HConstants.HBASE_NON_USER_TABLE_DIRS.contains(cfStatus.getPath().getName())) { continue; } FileStatus[] storeFileLists = fs.listStatus(cfStatus.getPath()); if (null == storeFileLists) { continue; } for (FileStatus storeFile : storeFileLists) { BlockLocation[] blkLocations = fs.getFileBlockLocations(storeFile, 0, storeFile.getLen()); if (null == blkLocations) { continue; } totalBlkCount += blkLocations.length; for (BlockLocation blk : blkLocations) { for (String host : blk.getHosts()) { AtomicInteger count = blockCountMap.get(host); if (count == null) { count = new AtomicInteger(0); blockCountMap.put(host, count); } count.incrementAndGet(); } } } } if (regionToBestLocalityRSMapping != null) { int largestBlkCount = 0; String hostToRun = null; for (Map.Entry<String, AtomicInteger> entry : blockCountMap.entrySet()) { String host = entry.getKey(); int tmp = entry.getValue().get(); if (tmp > largestBlkCount) { largestBlkCount = tmp; hostToRun = host; } } // empty regions could make this null if (null == hostToRun) { return; } if (hostToRun.endsWith(".")) { hostToRun = hostToRun.substring(0, hostToRun.length() - 1); } String name = tableName + ":" + regionPath.getName(); synchronized (regionToBestLocalityRSMapping) { regionToBestLocalityRSMapping.put(name, hostToRun); } } if (regionDegreeLocalityMapping != null && totalBlkCount > 0) { Map<String, Float> hostLocalityMap = new HashMap<String, Float>(); for (Map.Entry<String, AtomicInteger> entry : blockCountMap.entrySet()) { String host = entry.getKey(); if (host.endsWith(".")) { host = host.substring(0, host.length() - 1); } // Locality is fraction of blocks local to this host. float locality = ((float) entry.getValue().get()) / totalBlkCount; hostLocalityMap.put(host, locality); } // Put the locality map into the result map, keyed by the encoded name // of the region. regionDegreeLocalityMapping.put(regionPath.getName(), hostLocalityMap); } } catch (IOException e) { LOG.warn("Problem scanning file system", e); } catch (RuntimeException e) { LOG.warn("Problem scanning file system", e); } }
From source file:com.cloudera.livy.rsc.rpc.TestRpc.java
@Test public void testCloseListener() throws Exception { RpcServer server = autoClose(new RpcServer(emptyConfig)); Rpc[] rpcs = createRpcConnection(server); Rpc client = rpcs[1];//from ww w . j a v a 2 s . c o m final AtomicInteger closeCount = new AtomicInteger(); Utils.addListener(client.getChannel().closeFuture(), new FutureListener<Void>() { @Override public void onSuccess(Void unused) { closeCount.incrementAndGet(); } }); client.close(); client.close(); assertEquals(1, closeCount.get()); }
From source file:com.streamsets.pipeline.stage.origin.spooldir.TestWholeFileSpoolDirSource.java
@Test public void testWholeFileRecordsForFile() throws Exception { Path sourcePath = Paths.get(testDir + "/source.txt"); Files.write(sourcePath, "Sample Text 1".getBytes()); Files.setAttribute(sourcePath, "posix:permissions", ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ)); SpoolDirSource source = createSource(); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane") .setOnRecordError(OnRecordError.TO_ERROR).build(); final List<Record> records = Collections.synchronizedList(new ArrayList<>(10)); AtomicInteger batchCount = new AtomicInteger(0); runner.runInit();/* w w w. j a v a 2 s. co m*/ try { runner.runProduce(new HashMap<>(), 10, output2 -> { synchronized (records) { records.addAll(output2.getRecords().get("lane")); } batchCount.incrementAndGet(); runner.setStop(); }); runner.waitOnProduce(); Assert.assertNotNull(records); Assert.assertEquals(1, records.size()); Record record = records.get(0); Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH)); Assert.assertTrue(record.has(FileRefUtil.FILE_REF_FIELD_PATH)); Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType()); Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType()); Map<String, Object> metadata = Files.readAttributes(sourcePath, "posix:*"); Assert.assertTrue(record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getValueAsMap().keySet() .containsAll(metadata.keySet())); //Check permissions Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS)); Assert.assertEquals("rwxr-----", record .get(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS).getValueAsString()); Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType()); Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType()); } finally { runner.runDestroy(); } }
From source file:com.predic8.membrane.core.interceptor.apimanagement.AMRateLimitInterceptorTest.java
@Test public void testHandleRequestRateLimit5SecondConcurrency() throws Exception { final Exchange exc = new Exchange(null); exc.setResponse(Response.ResponseBuilder.newInstance().build()); exc.setProperty(Exchange.API_KEY, "junit"); exc.setRule(new ServiceProxy()); exc.getRule().setName("junit API"); final AMRateLimiter rli = new AMRateLimiter(); ApiManagementConfiguration amc = new ApiManagementConfiguration(System.getProperty("user.dir"), "src\\test\\resources\\apimanagement\\api.yaml"); rli.setAmc(amc);//from w ww . j a v a 2 s . co m ArrayList<Thread> threads = new ArrayList<Thread>(); final AtomicInteger continues = new AtomicInteger(); final AtomicInteger returns = new AtomicInteger(); for (int i = 0; i < 1000; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { try { Outcome out = rli.handleRequest(exc); if (out == Outcome.CONTINUE) { continues.incrementAndGet(); } else if (out == Outcome.RETURN) { returns.incrementAndGet(); } } catch (Exception e) { e.printStackTrace(); } } }); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } assertEquals(5, continues.get()); assertEquals(995, returns.get()); Thread.sleep(2000); assertEquals(Outcome.CONTINUE, rli.handleRequest(exc)); }
From source file:com.opengamma.financial.currency.AbstractCurrencyMatrix.java
protected void addConversion(final Currency source, final Currency target, final CurrencyMatrixValue rate) { ArgumentChecker.notNull(source, "source"); ArgumentChecker.notNull(target, "target"); ArgumentChecker.notNull(rate, "rate"); ConcurrentHashMap<Currency, CurrencyMatrixValue> conversions = _values.get(source); if (conversions == null) { conversions = new ConcurrentHashMap<Currency, CurrencyMatrixValue>(); final ConcurrentHashMap<Currency, CurrencyMatrixValue> newConversions = _values.putIfAbsent(source, conversions);/* w ww .ja va 2 s .c o m*/ if (newConversions != null) { conversions = newConversions; } } if (conversions.put(target, rate) == null) { // Added something to the map, so increase the target's reference count AtomicInteger targetCount = _targets.get(target); if (targetCount == null) { targetCount = new AtomicInteger(1); targetCount = _targets.putIfAbsent(target, targetCount); if (targetCount != null) { // Another thread already inserted the reference count if (targetCount.incrementAndGet() == 1) { // Another thread may have removed the last reference, confirm and re-insert atomically against "remove" synchronized (targetCount) { if (targetCount.get() > 0) { _targets.putIfAbsent(target, targetCount); } } } } } else { if (targetCount.incrementAndGet() == 1) { // Another thread may have removed the last reference, confirm and re-insert atomically against "remove" synchronized (targetCount) { if (targetCount.get() > 0) { _targets.putIfAbsent(target, targetCount); } } } } } }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java
private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, AtomicInteger maxConcurrentCount, Random random, int maxAllowed) throws Exception { try {/*from w w w . jav a2 s . c o m*/ Assert.assertTrue(lock.acquire(10, TimeUnit.SECONDS)); int localConcurrentCount; synchronized (this) { localConcurrentCount = concurrentCount.incrementAndGet(); if (localConcurrentCount > maxConcurrentCount.get()) { maxConcurrentCount.set(localConcurrentCount); } } Assert.assertTrue(localConcurrentCount <= maxAllowed, "" + localConcurrentCount); Thread.sleep(random.nextInt(9) + 1); } finally { synchronized (this) { concurrentCount.decrementAndGet(); lock.release(); } } }
From source file:com.ethercamp.harmony.service.WalletService.java
@PostConstruct public void init() { addresses.clear();/*from w ww.ja v a 2 s. c o m*/ final AtomicInteger index = new AtomicInteger(); Arrays.asList(keystore.listStoredKeys()) .forEach(a -> addresses.put(cleanAddress(a), "Account " + index.incrementAndGet())); fileSystemWalletStore.fromStore().stream().forEach(a -> addresses.put(a.address, a.name)); // workaround issue in ethereumJ-core, where single miner could never got sync done event if (config.minerStart()) { subscribeOnce(); } else { ethereum.addListener(new EthereumListenerAdapter() { @Override public void onSyncDone(SyncState state) { if (state == SyncState.UNSECURE || state == SyncState.COMPLETE) { subscribeOnce(); } } }); } }
From source file:net.nfpj.webcounter.dm.MemCounterDM.java
@Override public Counter increment(String name, boolean createIfNotExist) { if (name == null || name.isEmpty()) { throw new NullPointerException("Name cannot be null"); }// w w w . j ava 2 s . c om AtomicInteger ai = counters.get(name); if (ai == null) { if (createIfNotExist) { AtomicInteger existing = counters.putIfAbsent(name, ai = new AtomicInteger(0)); if (existing != null) { ai = existing; } } else { return null; } } return new Counter(name, ai.incrementAndGet()); }
From source file:org.apache.servicecomb.config.TestConfigUtil.java
@Test public void destroyConfigCenterConfigurationSource() { AtomicInteger count = new AtomicInteger(); ConfigCenterConfigurationSource source = new MockUp<ConfigCenterConfigurationSource>() { @Mock//from ww w . j a va2s .co m void destroy() { count.incrementAndGet(); } }.getMockInstance(); new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class); result = Arrays.asList(source, source); } }; ConfigUtil.destroyConfigCenterConfigurationSource(); Assert.assertEquals(2, count.get()); }
From source file:io.undertow.server.handlers.caching.CacheHandlerTestCase.java
@Test public void testBasicPathBasedCaching() throws IOException { final AtomicInteger responseCount = new AtomicInteger(); final HttpHandler messageHandler = new HttpHandler() { @Override//from ww w .j a va2s .c o m public void handleRequest(final HttpServerExchange exchange) throws Exception { final ResponseCache cache = exchange.getAttachment(ResponseCache.ATTACHMENT_KEY); if (!cache.tryServeResponse()) { final String data = "Response " + responseCount.incrementAndGet(); exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, data.length() + ""); exchange.getResponseSender().send(data); } } }; final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(100, 10, 1000), messageHandler); DefaultServer.setRootHandler(cacheHandler); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); //it takes 5 hits to make an entry actually get cached for (int i = 1; i <= 5; ++i) { HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Response " + i, HttpClientUtils.readResponse(result)); } HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result)); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result)); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result)); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path2"); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("Response 6", HttpClientUtils.readResponse(result)); } finally { client.getConnectionManager().shutdown(); } }