List of usage examples for java.util.concurrent ConcurrentHashMap ConcurrentHashMap
public ConcurrentHashMap()
From source file:nl.esciencecenter.osmium.job.XenonManager.java
/** * Sets preferences in GAT context and initializes a broker. * * @param configuration Configuration for Xenon * @throws XenonException if Xenon could not be configured *//*from w ww .j ava 2 s. c o m*/ public XenonManager(XenonConfiguration configuration) throws XenonException { this.configuration = configuration; xenon = XenonFactory.newXenon(configuration.getPreferences()); scheduler = newScheduler(); sandboxRootPath = newSandboxRootPath(); jobs = new ConcurrentHashMap<String, SandboxedJob>(); executor = Executors.newSingleThreadScheduledExecutor(); PollConfiguration pollConf = configuration.getPoll(); poller = new JobsPoller(jobs, pollConf, xenon); }
From source file:ar.com.zauber.commons.message.message.templates.MultipartSubjectMessageTemplate.java
/**Creates the MultipartSubjectMessageTemplate.*/ public MultipartSubjectMessageTemplate(final List<PartTemplate> templates, final PartTemplate subjectTemplate, final NotificationAddressFactory notificationAddressFactory, final PartTemplate replyToTemplate) { this(templates, subjectTemplate, notificationAddressFactory, replyToTemplate, new ConcurrentHashMap<String, String>()); }
From source file:io.druid.client.cache.MemcachedCache.java
public static MemcachedCache create(final MemcachedCacheConfig config) { final ConcurrentMap<String, AtomicLong> counters = new ConcurrentHashMap<>(); final ConcurrentMap<String, AtomicLong> meters = new ConcurrentHashMap<>(); final AbstractMonitor monitor = new AbstractMonitor() { final AtomicReference<Map<String, Long>> priorValues = new AtomicReference<Map<String, Long>>( new HashMap<String, Long>()); @Override//from w w w .j av a 2 s . c o m public boolean doMonitor(ServiceEmitter emitter) { final Map<String, Long> priorValues = this.priorValues.get(); final Map<String, Long> currentValues = getCurrentValues(); final ServiceMetricEvent.Builder builder = ServiceMetricEvent.builder(); for (Map.Entry<String, Long> entry : currentValues.entrySet()) { emitter.emit(builder.setDimension("memcached metric", entry.getKey()) .build("query/cache/memcached/total", entry.getValue())); final Long prior = priorValues.get(entry.getKey()); if (prior != null) { emitter.emit(builder.setDimension("memcached metric", entry.getKey()) .build("query/cache/memcached/delta", entry.getValue() - prior)); } } if (!this.priorValues.compareAndSet(priorValues, currentValues)) { log.error("Prior value changed while I was reporting! updating anyways"); this.priorValues.set(currentValues); } return true; } private Map<String, Long> getCurrentValues() { final ImmutableMap.Builder<String, Long> builder = ImmutableMap.builder(); for (Map.Entry<String, AtomicLong> entry : counters.entrySet()) { builder.put(entry.getKey(), entry.getValue().get()); } for (Map.Entry<String, AtomicLong> entry : meters.entrySet()) { builder.put(entry.getKey(), entry.getValue().get()); } return builder.build(); } }; try { LZ4Transcoder transcoder = new LZ4Transcoder(config.getMaxObjectSize()); // always use compression transcoder.setCompressionThreshold(0); OperationQueueFactory opQueueFactory; long maxQueueBytes = config.getMaxOperationQueueSize(); if (maxQueueBytes > 0) { opQueueFactory = new MemcachedOperationQueueFactory(maxQueueBytes); } else { opQueueFactory = new LinkedOperationQueueFactory(); } final Predicate<String> interesting = new Predicate<String>() { // See net.spy.memcached.MemcachedConnection.registerMetrics() private final Set<String> interestingMetrics = ImmutableSet.of( "[MEM] Reconnecting Nodes (ReconnectQueue)", //"[MEM] Shutting Down Nodes (NodesToShutdown)", // Busted "[MEM] Request Rate: All", "[MEM] Average Bytes written to OS per write", "[MEM] Average Bytes read from OS per read", "[MEM] Average Time on wire for operations (s)", "[MEM] Response Rate: All (Failure + Success + Retry)", "[MEM] Response Rate: Retry", "[MEM] Response Rate: Failure", "[MEM] Response Rate: Success"); @Override public boolean apply(@Nullable String input) { return input != null && interestingMetrics.contains(input); } }; final MetricCollector metricCollector = new MetricCollector() { @Override public void addCounter(String name) { if (!interesting.apply(name)) { return; } counters.putIfAbsent(name, new AtomicLong(0L)); if (log.isDebugEnabled()) { log.debug("Add Counter [%s]", name); } } @Override public void removeCounter(String name) { if (log.isDebugEnabled()) { log.debug("Ignoring request to remove [%s]", name); } } @Override public void incrementCounter(String name) { if (!interesting.apply(name)) { return; } AtomicLong counter = counters.get(name); if (counter == null) { counters.putIfAbsent(name, new AtomicLong(0)); counter = counters.get(name); } counter.incrementAndGet(); if (log.isDebugEnabled()) { log.debug("Increment [%s]", name); } } @Override public void incrementCounter(String name, int amount) { if (!interesting.apply(name)) { return; } AtomicLong counter = counters.get(name); if (counter == null) { counters.putIfAbsent(name, new AtomicLong(0)); counter = counters.get(name); } counter.addAndGet(amount); if (log.isDebugEnabled()) { log.debug("Increment [%s] %d", name, amount); } } @Override public void decrementCounter(String name) { if (!interesting.apply(name)) { return; } AtomicLong counter = counters.get(name); if (counter == null) { counters.putIfAbsent(name, new AtomicLong(0)); counter = counters.get(name); } counter.decrementAndGet(); if (log.isDebugEnabled()) { log.debug("Decrement [%s]", name); } } @Override public void decrementCounter(String name, int amount) { if (!interesting.apply(name)) { return; } AtomicLong counter = counters.get(name); if (counter == null) { counters.putIfAbsent(name, new AtomicLong(0L)); counter = counters.get(name); } counter.addAndGet(-amount); if (log.isDebugEnabled()) { log.debug("Decrement [%s] %d", name, amount); } } @Override public void addMeter(String name) { if (!interesting.apply(name)) { return; } meters.putIfAbsent(name, new AtomicLong(0L)); if (log.isDebugEnabled()) { log.debug("Adding meter [%s]", name); } } @Override public void removeMeter(String name) { if (!interesting.apply(name)) { return; } if (log.isDebugEnabled()) { log.debug("Ignoring request to remove meter [%s]", name); } } @Override public void markMeter(String name) { if (!interesting.apply(name)) { return; } AtomicLong meter = meters.get(name); if (meter == null) { meters.putIfAbsent(name, new AtomicLong(0L)); meter = meters.get(name); } meter.incrementAndGet(); if (log.isDebugEnabled()) { log.debug("Increment counter [%s]", name); } } @Override public void addHistogram(String name) { log.debug("Ignoring add histogram [%s]", name); } @Override public void removeHistogram(String name) { log.debug("Ignoring remove histogram [%s]", name); } @Override public void updateHistogram(String name, int amount) { log.debug("Ignoring update histogram [%s]: %d", name, amount); } }; final ConnectionFactory connectionFactory = new MemcachedCustomConnectionFactoryBuilder() // 1000 repetitions gives us good distribution with murmur3_128 // (approx < 5% difference in counts across nodes, with 5 cache nodes) .setKetamaNodeRepetitions(1000).setHashAlg(MURMUR3_128) .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY) .setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT).setDaemon(true) .setFailureMode(FailureMode.Cancel).setTranscoder(transcoder).setShouldOptimize(true) .setOpQueueMaxBlockTime(config.getTimeout()).setOpTimeout(config.getTimeout()) .setReadBufferSize(config.getReadBufferSize()).setOpQueueFactory(opQueueFactory) .setMetricCollector(metricCollector).setEnableMetrics(MetricType.DEBUG) // Not as scary as it sounds .build(); final List<InetSocketAddress> hosts = AddrUtil.getAddresses(config.getHosts()); final Supplier<ResourceHolder<MemcachedClientIF>> clientSupplier; if (config.getNumConnections() > 1) { clientSupplier = new LoadBalancingPool<MemcachedClientIF>(config.getNumConnections(), new Supplier<MemcachedClientIF>() { @Override public MemcachedClientIF get() { try { return new MemcachedClient(connectionFactory, hosts); } catch (IOException e) { log.error(e, "Unable to create memcached client"); throw Throwables.propagate(e); } } }); } else { clientSupplier = Suppliers.<ResourceHolder<MemcachedClientIF>>ofInstance(StupidResourceHolder .<MemcachedClientIF>create(new MemcachedClient(connectionFactory, hosts))); } return new MemcachedCache(clientSupplier, config, monitor); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:com.kixeye.chassis.support.logging.FlumeLoggerLoader.java
@PostConstruct public void initialize() { multicaster.addApplicationListener(loggingListener); ConcurrentHashMap<String, String> flumeConfig = new ConcurrentHashMap<>(); List<String> sinks = new ArrayList<>(); for (String server : servers) { String sinkName = server.replace(":", "-").replace(".", "_"); String[] servers = server.split(":", 2); if (servers.length == 2) { flumeConfig.put(sinkName + ".type", "avro"); flumeConfig.put(sinkName + ".channels", "channel-" + name); flumeConfig.put(sinkName + ".hostname", servers[0]); flumeConfig.put(sinkName + ".port", servers[1]); } else {//from w ww.j a v a 2 s . c o m logger.error("Invalid server format [{}], should be [hostname:port]", server); } sinks.add(sinkName); } // force some properties flumeConfig.put("channel.type", "file"); flumeConfig.put("sinks", StringUtils.collectionToDelimitedString(sinks, " ")); flumeConfig.putIfAbsent("processor.type", serversUsage); flumeConfig.put("channel.checkpointDir", SystemPropertyUtils.resolvePlaceholders("${user.dir}/flume-data/checkpoint")); flumeConfig.put("channel.dataDirs", SystemPropertyUtils.resolvePlaceholders("${user.dir}/flume-data/data")); agent = new EmbeddedAgent(name); agent.configure(flumeConfig); agent.start(); appender = new FlumeLogAppender(agent, serviceName); installFlumeAppender(); }
From source file:com.doctor.other.concurrent_hash_map_based_table.ConcurrentHashMapBasedTable.java
/** * //w ww. j ava 2s . c om * @param rowKey * @param columnKey * @param timesplice * ?:201572701 * @param value * @return */ public boolean put(final String rowKey, final String columnKey, final String timesplice, final T value) { Preconditions.checkState(StringUtils.isNotBlank(rowKey), "rowKey is blank"); Preconditions.checkState(StringUtils.isNotBlank(columnKey), "columnKey is blank"); Preconditions.checkState(StringUtils.isNotBlank(timesplice), "timesplice is blank"); Preconditions.checkNotNull(value, "value is null"); ConcurrentHashMap<String, ConcurrentSkipListMap<String, ConcurrentSet<T>>> row = table.get(rowKey); if (row == null) { table.putIfAbsent(rowKey, new ConcurrentHashMap<String, ConcurrentSkipListMap<String, ConcurrentSet<T>>>()); } row = table.get(rowKey); ConcurrentSkipListMap<String, ConcurrentSet<T>> column = row.get(columnKey); if (column == null) { row.putIfAbsent(columnKey, new ConcurrentSkipListMap<String, ConcurrentSet<T>>()); } column = row.get(columnKey); ConcurrentSet<T> values = column.get(timesplice); if (values == null) { column.putIfAbsent(timesplice, new ConcurrentSet<>()); } values = column.get(timesplice); return values.add(value); }
From source file:com.kylinolap.rest.service.BasicService.java
public void resetOLAPDataSources() { // brutal, yet simplest way logger.info("resetOLAPDataSources is called."); olapDataSources = new ConcurrentHashMap<String, DataSource>(); }
From source file:com.kylinolap.dict.DictionaryManager.java
private DictionaryManager(KylinConfig config) { this.config = config; dictCache = new ConcurrentHashMap<String, DictionaryInfo>(); }
From source file:com.turn.ttorrent.tracker.TrackedTorrent.java
/** * Create a new tracked torrent from meta-info binary data. * * @param torrent The meta-info byte data. * @throws IOException When the info dictionary can't be * encoded and hashed back to create the torrent's SHA-1 hash. *//*from w w w . j ava 2 s.c om*/ public TrackedTorrent(byte[] torrent) throws IOException, NoSuchAlgorithmException { super(torrent, false); this.peers = new ConcurrentHashMap<String, TrackedPeer>(); this.answerPeers = TrackedTorrent.DEFAULT_ANSWER_NUM_PEERS; this.announceInterval = TrackedTorrent.DEFAULT_ANNOUNCE_INTERVAL_SECONDS; }
From source file:ai.grakn.engine.tasks.manager.StandaloneTaskManager.java
public StandaloneTaskManager(EngineID engineId) { this.engineID = engineId; instantiatedTasks = new ConcurrentHashMap<>(); stateStorage = new TaskStateInMemoryStore(); stateUpdateLock = new ReentrantLock(); ConfigProperties properties = ConfigProperties.getInstance(); schedulingService = Executors.newScheduledThreadPool(1); executorService = Executors.newFixedThreadPool(properties.getAvailableThreads()); }
From source file:com.clustercontrol.repository.action.GetNodeList.java
/** * property????????//from ww w .ja v a 2 s . com * * @param managerName ??? * @param property * @return */ public List<NodeInfo> get(String managerName, Property property) { PropertyUtil.deletePropertyDefine(property); List<NodeInfo> records = null; Map<String, String> errorMsgs = new ConcurrentHashMap<>(); try { RepositoryEndpointWrapper wrapper = RepositoryEndpointWrapper.getWrapper(managerName); NodeInfo nodeInfo = null; nodeInfo = NodePropertyUtil.property2node(property); records = wrapper.getFilterNodeList(nodeInfo); } catch (InvalidRole_Exception e) { errorMsgs.put(managerName, Messages.getString("message.accesscontrol.16")); } catch (Exception e) { m_log.warn("getAll(), " + e.getMessage(), e); errorMsgs.put(managerName, Messages.getString("message.hinemos.failure.unexpected") + ", " + HinemosMessage.replace(e.getMessage())); } // if (0 < errorMsgs.size()) { UIManager.showMessageBox(errorMsgs, true); } return records; }