Example usage for java.util.concurrent ConcurrentHashMap ConcurrentHashMap

List of usage examples for java.util.concurrent ConcurrentHashMap ConcurrentHashMap

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentHashMap ConcurrentHashMap.

Prototype

public ConcurrentHashMap() 

Source Link

Document

Creates a new, empty map with the default initial table size (16).

Usage

From source file:com.athena.sqs.MessageAggregator.java

/**
 * Aggregate splitted messages into single message.
 * @param rawData base64 string//from www  . j  a  v a 2  s  .com
 * @throws MessageException
 */
public void aggregate(String rawString) throws MessageException {
    try {
        BASE64Decoder decoder = new BASE64Decoder();

        int index = rawString.indexOf(MessageContext.DATA_DELIMITER);

        // 1. Split header
        String[] header = parseHeader(rawString.substring(0, index));
        String content = rawString.substring(index + 2);

        // 2. Assign header value to local variable
        MessageTransferType transferType = MessageTransferType.valueOf(header[0]);
        String businessName = header[1];
        String transactionId = header[2];
        MessageSplitType splitType = MessageSplitType.valueOf(header[3]);
        int current = Integer.parseInt(header[4]);
        int total = Integer.parseInt(header[5]);

        // 3 Check Message Single
        switch (splitType) {
        case SINGLE:
            // TODO single message work
            doProcess(transactionId, new String(decoder.decodeBuffer(content)));
            return;
        case MULTI:
            break;
        }

        logger.debug("Transaction ID : " + transactionId);

        // 4. Check Message Order
        // If transaction id is not exist in txMap, create new tx map object
        if (!txMap.containsKey(transactionId)) {
            ConcurrentHashMap<Integer, String> orderedMessages = new ConcurrentHashMap<Integer, String>();
            orderedMessages.put(current, content);

            txMap.put(transactionId, orderedMessages);
        } else {
            // Already same transaction message was inserted
            ConcurrentHashMap<Integer, String> orderedMessages = txMap.get(transactionId);
            orderedMessages.put(current, content);

            // Message compare
            if (orderedMessages.size() == total) {
                // All messages arrived
                Object[] key = orderedMessages.keySet().toArray();
                Arrays.sort(key);

                String finalMessage = "";
                for (int i = 0; i < key.length; i++) {
                    finalMessage += orderedMessages.get(key[i]);
                }

                logger.debug("===== [ " + transactionId + "] ======");
                logger.debug(new String(decoder.decodeBuffer(finalMessage)));
                boolean isDelete = txMap.remove(transactionId, orderedMessages);
                if (!isDelete) {
                    throw new MessageException("Can't delete message from transaction map");
                }

                doProcess(transactionId, new String(decoder.decodeBuffer(finalMessage)));
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ArrayMap.java

private synchronized void synchronizedPut(K key, V value) {
    for (int i = 0; i < arrayCount; i++) {
        if (arrayEntries[i].getKey().equals(key)) {
            arrayEntries[i].setNewValue(value);
            return;
        }/*from   w ww.ja  v  a 2  s.c o m*/
    }
    if (arrayCount != -1) {
        if (arrayCount < arrayEntries.length) {
            arrayEntries[arrayCount++] = new ArrayEntry<K, V>(key, value);
        } else {
            propertyMap = new ConcurrentHashMap<K, V>();
            for (int i = 0; i < arrayCount; i++) {
                propertyMap.put(arrayEntries[i].getKey(), arrayEntries[i].getValue());
            }
            arrayEntries = null;
            arrayCount = -1;
            propertyMap.put(key, value);
        }
    } else {
        propertyMap.put(key, value);
    }
}

From source file:com.ning.metrics.collector.processing.db.model.TestRollUpDailyCounter.java

@Test
public void testGroupDailyCounterList() throws Exception {
    List<CounterEventData> dailyCounterList = new ArrayList<CounterEventData>();

    dailyCounterList.add(prepareCounterEventData("member123", Arrays.asList("pageView", "trafficMobile")));
    dailyCounterList.add(//from ww w. j  a v  a  2  s .  c  o  m
            prepareCounterEventData("member123", Arrays.asList("pageView", "trafficTablet", "contribution")));

    dailyCounterList.add(prepareCounterEventData("member321", Arrays.asList("pageView", "trafficMobile")));
    dailyCounterList.add(prepareCounterEventData("member321", Arrays.asList("pageView", "trafficMobile")));

    Map<String, CounterEventData> groupMap = new ConcurrentHashMap<String, CounterEventData>();

    for (CounterEventData counterEventData : dailyCounterList) {
        CounterEventData groupedData = groupMap
                .get(counterEventData.getUniqueIdentifier() + counterEventData.getFormattedDate());
        if (Objects.equal(null, groupedData)) {
            groupMap.put(counterEventData.getUniqueIdentifier() + counterEventData.getFormattedDate(),
                    counterEventData);
            continue;
        }

        groupedData.mergeCounters(counterEventData.getCounters());
        groupMap.put(counterEventData.getUniqueIdentifier() + counterEventData.getFormattedDate(), groupedData);
    }

    Assert.assertEquals(groupMap.values().size(), 2);
    Assert.assertEquals(groupMap.values().iterator().next().getCounters().get("pageView"), new Integer(2));

}

From source file:com.vmware.identity.idm.server.RsaAuthSessionCache.java

public void addSession(String tenantName, String sessionId, AuthenticationSession session) {
    String normalizedTenant = tenantName.toLowerCase();
    ConcurrentHashMap<String, AuthenticationSession> sessionCache = _rsaSessionCacheLookup
            .get(normalizedTenant);//w  w  w .j av a 2  s  .c  o m

    if (sessionCache == null) {
        sessionCache = new ConcurrentHashMap<String, AuthenticationSession>();
        _rsaSessionCacheLookup.put(normalizedTenant, sessionCache);
        logger.debug("Added RSA session cache for : " + tenantName);
    }
    sessionCache.put(sessionId, session);

    logger.debug("Added RSA session to cache. sessionID: " + sessionId);
}

From source file:rk.java.compute.cep.ComputeService.java

public ComputeService(BlockingQueue<IPriceTick> queue, final int numberOfTickSources,
        IPriceEventSink eventbus) {/* w w w  . j  a v a  2 s.co m*/
    this.feedQueue = queue;
    this.numberOfTickSources = numberOfTickSources;
    this.eventbus = eventbus;
    this.handlerCache = new ConcurrentHashMap<String, Compute>();
    this.stopWatch = new StopWatch("Dispatcher Task");
    executorService = Executors.newCachedThreadPool();
    ecs = new ExecutorCompletionService<StopWatch>(executorService);
    dispatchTaskFuture = ecs.submit(new Callable<StopWatch>() {
        @Override
        public StopWatch call() throws Exception {
            stopWatch.start();
            run();
            stopWatch.stop();
            return stopWatch;
        }
    });
}

From source file:com.zimbra.cs.datasource.DataSourceManager.java

private static <E> Set<E> newConcurrentHashSet() {
    return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}

From source file:ai.susi.json.JsonDataset.java

/**
 * define a data set: an indexed JsonDump where the index is held in RAM
 * @param dump_dir the path where the subdirectories for this data set shall be stored
 * @param dump_file_prefix a prefix for the file names
 * @param index_keys the names of the json property keys where their content shall be indexed by this field
 * @param mode the indexing mode, either completely in RAM with Mode.COMPRESSED or with file handles with Mode.REWRITABLE
 * @throws IOException// w w w  .ja  va2 s  .co m
 */
public JsonDataset(File dump_dir, String dump_file_prefix, Column[] columns, String dateFieldName,
        String dateFieldFormat, JsonRepository.Mode mode, final boolean dailyDump, int count)
        throws IOException {

    // initialize class objects
    int concurrency = Runtime.getRuntime().availableProcessors();
    this.indexDump = new JsonRepository(dump_dir, dump_file_prefix, null, mode, dailyDump, concurrency);
    this.index = new ConcurrentHashMap<>();
    this.minifier = new JsonMinifier();
    this.columns = new HashMap<>();
    this.dateFieldName = dateFieldName == null ? "" : dateFieldName;
    this.dateFieldFormat = this.dateFieldName.length() == 0 ? null : new SimpleDateFormat(dateFieldFormat);
    for (Column column : columns)
        this.columns.put(column.key, column.caseInsensitive);

    // assign for each index key one JsonFactory index
    for (Column col : columns)
        this.index.put(col.key, new JsonFactoryIndex());

    // start reading of the JsonDump
    final Collection<File> dumps = indexDump.getOwnDumps(count);

    // for each reader one threqd is started which does Json parsing and indexing
    if (dumps != null)
        for (final File dump : dumps) {
            final JsonReader reader = indexDump.getDumpReader(dump);
            DAO.log("loading " + reader.getName());
            Thread[] indexerThreads = new Thread[concurrency];
            for (int i = 0; i < concurrency; i++) {
                indexerThreads[i] = new Thread() {
                    public void run() {
                        JsonFactory jsonHandle;
                        try {
                            while ((jsonHandle = reader.take()) != JsonStreamReader.POISON_JSON_MAP) {
                                JSONObject op = jsonHandle.getJSON();
                                JsonFactory jsonFactory;
                                if (jsonHandle instanceof JsonRandomAccessFile.JsonHandle) {
                                    JsonRandomAccessFile.JsonHandle handle = (JsonRandomAccessFile.JsonHandle) jsonHandle;
                                    assert reader instanceof JsonRandomAccessFile;
                                    // create the file json handle which does not contain the json any more
                                    // but only the file handle
                                    jsonFactory = ((JsonRandomAccessFile) reader)
                                            .getJsonFactory(handle.getIndex(), handle.getLength());
                                } else {
                                    assert JsonDataset.this.indexDump
                                            .getMode() == JsonRepository.COMPRESSED_MODE;
                                    // create the json minifier object which contains the json in minified version
                                    // before we create the minifier, we remove the meta keys from the json to further minify it
                                    for (byte[] meta_key : JsonRepository.META_KEYS) {
                                        op.remove(new String(meta_key, StandardCharsets.US_ASCII));
                                    }
                                    jsonFactory = JsonDataset.this.minifier.minify(op);
                                }
                                // the resulting json factory is written to each search index
                                for (Map.Entry<String, Boolean> column : JsonDataset.this.columns.entrySet()) {
                                    String searchKey = column.getKey();
                                    boolean case_insensitive = column.getValue();
                                    JsonFactoryIndex factoryIndex = JsonDataset.this.index.get(searchKey);
                                    Object searchValue = op.has(searchKey) ? op.get(searchKey) : null;
                                    if (searchValue != null) {
                                        if (searchValue instanceof String) {
                                            factoryIndex
                                                    .put(case_insensitive ? ((String) searchValue).toLowerCase()
                                                            : (String) searchValue, jsonFactory);
                                        } else {
                                            factoryIndex.put(searchValue, jsonFactory);
                                        }
                                    }
                                }
                            }
                        } catch (InterruptedException e) {
                            Log.getLog().warn(e);
                        } catch (IOException e) {
                            Log.getLog().warn(e);
                        }
                    }
                };
                indexerThreads[i].start();
            }
            // wait for the completion of each task
            for (int i = 0; i < concurrency; i++) {
                try {
                    indexerThreads[i].join();
                } catch (InterruptedException e) {
                }
            }
        }
}

From source file:com.netflix.config.ConcurrentMapConfiguration.java

/**
 * Create an instance with an empty map.
 *//*from w w  w  . j a va2 s .  c  o  m*/
public ConcurrentMapConfiguration() {
    map = new ConcurrentHashMap<String, Object>();
    for (int i = 0; i < NUM_LOCKS; i++) {
        locks[i] = new ReentrantLock();
    }
}

From source file:com.haulmont.multitenancy.TenantsRoutingDatasource.java

@Override
public void afterPropertiesSet() throws Exception {
    dataSources = new ConcurrentHashMap<>();
    defaultDataSource = createDataSource(defaultDbAddress);

    try {//ww  w  .  j  ava  2s.c  o m
        Context context = new InitialContext();
        String path = AppContext.getProperty(jndiNameAppProperty);
        if (path == null)
            throw new IllegalStateException("Property " + jndiNameAppProperty + " is not set");
        context.bind(path, this);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:ExpiringMap.java

/**
 * Creates a new instance of ExpiringMap using the supplied values and 
 * a {@link ConcurrentHashMap} for the internal data structure.
 *
 * @param timeToLive//from  w  w  w . ja  va2  s .  c  om
 *  The time-to-live value (seconds)
 * @param expirationInterval
 *  The time between checks to see if a value should be removed (seconds)
 */
public ExpiringMap(int timeToLive, int expirationInterval) {
    this(new ConcurrentHashMap<K, ExpiringObject>(), new CopyOnWriteArrayList<ExpirationListener<V>>(),
            timeToLive, expirationInterval);
}