List of usage examples for java.util.concurrent.atomic AtomicInteger AtomicInteger
public AtomicInteger(int initialValue)
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);//from w w w .java 2s . 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.haulmont.cuba.core.app.scheduling.RunnerBean.java
@PostConstruct public void init() { int nThreads = configuration.getConfig(ServerConfig.class).getSchedulingThreadPoolSize(); executorService = Executors.newFixedThreadPool(nThreads, new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); @Override// w w w . j a v a 2 s. co m public Thread newThread(@Nonnull Runnable r) { Thread thread = new Thread(r, "ScheduledRunnerThread-" + threadNumber.getAndIncrement()); thread.setDaemon(true); return thread; } }); }
From source file:com.taobao.pushit.server.listener.ConnectionNumberListener.java
/** * , //from www .j a va 2 s .c o m */ public void onConnectionCreated(Connection conn) { // IP String remoteIp = this.getRemoteIp(conn); try { // IPserver, AtomicInteger connNum = this.connectionIpNumMap.get(remoteIp); if (connNum == null) { AtomicInteger newConnNum = new AtomicInteger(0); AtomicInteger oldConnNum = this.connectionIpNumMap.putIfAbsent(remoteIp, newConnNum); if (oldConnNum != null) { connNum = oldConnNum; } else { connNum = newConnNum; } } connNum.incrementAndGet(); // , if (isOverflow || connNum.get() > this.connThreshold) { // log.warn("pushit-server, , :" + connNum.get() + ",:" + this.connThreshold); conn.close(false); } } catch (NotifyRemotingException e) { log.error(", remoteIp=" + remoteIp, e); } catch (Exception e) { log.error(", remoteIp=" + remoteIp, e); } }
From source file:com.aol.advertising.qiao.util.CommonUtils.java
public static ScheduledExecutorService createScheduledExecutorService(final int poolSz, final String threadName) { return Executors.newScheduledThreadPool(poolSz, new ThreadFactory() { private AtomicInteger threadNum = new AtomicInteger(0); @Override/*from ww w . ja v a2 s. c o m*/ public Thread newThread(Runnable r) { if (poolSz == 1) return new Thread(r, threadName); else return new Thread(r, threadName + threadNum.incrementAndGet()); } }); }
From source file:com.indeed.lsmtree.recordlog.TestBlockCompressedRecordFile.java
public void testRandom() throws IOException { final BlockCompressedRecordFile<String> recordFile = createBlockCache(); final AtomicInteger done = new AtomicInteger(8); for (int i = 0; i < 8; i++) { final int index = i; new Thread(new Runnable() { @Override// w ww.jav a 2 s. c o m public void run() { try { final Random r = new Random(index); for (int i = 0; i < 10000000; i++) { int rand = r.nextInt(positions.size()); assertTrue(recordFile.get(positions.get(rand)).equals(strings.get(rand))); } } catch (IOException e) { throw new RuntimeException(e); } finally { done.decrementAndGet(); } } }).start(); } while (done.get() > 0) { Thread.yield(); } recordFile.close(); }
From source file:com.sworddance.taskcontrol.TaskControl.java
@SuppressWarnings("unchecked") public TaskControl(Comparator<PrioritizedTask> activeComparator, int maxThreads, ThreadFactory threadFactory, Log log) {//from ww w .ja v a 2s . co m this.log = log; ApplicationIllegalArgumentException.notNull(activeComparator, "activeComparator"); this.eligibleTasks = new PriorityBlockingQueue<PrioritizedTask>(20, activeComparator); this.stateChangeNotificator = new ReentrantLock(); this.newTasks = this.stateChangeNotificator.newCondition(); this.runningTasks = new AtomicInteger(0); this.threadFactory = threadFactory; int keepAliveTime = 10; int corePoolSize = 1; this.executor = new ThreadPoolExecutor(corePoolSize, Math.max(corePoolSize, maxThreads), keepAliveTime, MICROSECONDS, (BlockingQueue) this.eligibleTasks, threadFactory); this.stayActive = true; }
From source file:com.thoughtworks.go.buildsession.ExecCommandExecutor.java
private int executeCommandLine(final BuildSession buildSession, final CommandLine commandLine) { final AtomicInteger exitCode = new AtomicInteger(-1); final CountDownLatch canceledOrDone = new CountDownLatch(1); buildSession.submitRunnable(new Runnable() { @Override//from ww w.j a v a2 s . c o m public void run() { try { exitCode.set(commandLine.run(buildSession.processOutputStreamConsumer(), null)); } catch (CommandLineException e) { LOG.error("Command failed", e); String message = format( "Error happened while attempting to execute '%s'. \nPlease make sure [%s] can be executed on this agent.\n", commandLine.toStringForDisplay(), commandLine.getExecutable()); String path = System.getenv("PATH"); buildSession.println(message); buildSession.println(format("[Debug Information] Environment variable PATH: %s", path)); LOG.error(format("[Command Line] %s. Path: %s", message, path)); } finally { canceledOrDone.countDown(); } } }); Future<?> cancelMonitor = buildSession.submitRunnable(new Runnable() { @Override public void run() { try { buildSession.waitUntilCanceled(); } catch (InterruptedException e) { // ignore } finally { canceledOrDone.countDown(); } } }); try { canceledOrDone.await(); } catch (InterruptedException e) { LOG.error("Building thread interrupted", e); } cancelMonitor.cancel(true); return exitCode.get(); }
From source file:io.apiman.gateway.engine.vertx.polling.URILoadingRegistry.java
public static void reloadData(IAsyncHandler<Void> doneHandler) { synchronized (URILoadingRegistry.class) { if (instance == null) { doneHandler.handle((Void) null); return; }/*from w ww. j av a2 s . c om*/ Map<URILoadingRegistry, IAsyncResultHandler<Void>> regs = instance.handlers; Vertx vertx = instance.vertx; URI uri = instance.uri; Map<String, String> config = instance.config; AtomicInteger ctr = new AtomicInteger(regs.size()); OneShotURILoader newLoader = new OneShotURILoader(vertx, uri, config); regs.entrySet().stream().forEach(pair -> { // Clear the registrys' internal maps to prepare for reload. // NB: If we add production hot reloading, we'll need to work around this (e.g. clone?). pair.getKey().getMap().clear(); // Re-subscribe the registry. newLoader.subscribe(pair.getKey(), result -> { checkAndFlip(ctr.decrementAndGet(), newLoader, doneHandler); }); }); checkAndFlip(ctr.get(), newLoader, doneHandler); } }
From source file:com.sixt.service.framework.kafka.messaging.KafkaFailoverIntegrationTest.java
@Test public void manualKafkaTest() throws InterruptedException { ServiceProperties serviceProperties = fillServiceProperties(); // Topics are created with 3 partitions - see docker-compose-kafkafailover-integrationtest.yml Topic ping = new Topic("ping"); Topic pong = new Topic("pong"); AtomicInteger sentMessages = new AtomicInteger(0); AtomicInteger sendFailures = new AtomicInteger(0); AtomicInteger recievedMessages = new AtomicInteger(0); Producer producer = new ProducerFactory(serviceProperties).createProducer(); final AtomicBoolean produceMessages = new AtomicBoolean(true); // Produce messages until test tells producer to stop. ExecutorService producerExecutor = Executors.newSingleThreadExecutor(); producerExecutor.submit(new Runnable() { @Override//from w ww . j a v a 2s . c o m public void run() { OrangeContext context = new OrangeContext(); Sleeper sleeper = new Sleeper(); while (produceMessages.get()) { try { String key = RandomStringUtils.randomAscii(5); SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build(); Message request = Messages.requestFor(ping, pong, key, payload, context); producer.send(request); sentMessages.incrementAndGet(); sleeper.sleepNoException(1000); } catch (Throwable t) { sendFailures.incrementAndGet(); logger.error("Caught exception in producer loop", t); } } } }); Consumer consumer = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class, new MessageHandler<SayHelloToCmd>() { @Override public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) { recievedMessages.incrementAndGet(); } }).consumerForTopic(ping, new DiscardFailedMessages()); // Wait to allow manual fiddling with Kafka. Sync with global test timeout above. Thread.sleep(2 * 60 * 1000); produceMessages.set(false); producer.shutdown(); Thread.sleep(10_000); consumer.shutdown(); logger.info("sentMessages: " + sentMessages.get()); logger.info("sendFailures: " + sendFailures.get()); logger.info("recievedMessages: " + recievedMessages.get()); }
From source file:com.flowpowered.commons.StringToUniqueIntegerMap.java
/** * @param parent the parent of this map// w ww . j ava 2 s .c o m * @param store the store to store ids * @param minId the lowest valid id for dynamic allocation (ids below this are assumed to be reserved) * @param maxId the highest valid id + 1 * @param name The name of this StringToUniqueIntegerMap */ public StringToUniqueIntegerMap(StringToUniqueIntegerMap parent, SimpleStore<Integer> store, int minId, int maxId, String name) { super(store, name); this.parent = parent; if (this.parent != null) { thisToParentMap = new AtomicReferenceArray<>(maxId); parentToThisMap = new AtomicReferenceArray<>(maxId); } else { thisToParentMap = null; parentToThisMap = null; } this.minId = minId; this.maxId = maxId; nextId = new AtomicInteger(minId); }