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.astamuse.asta4d.web.util.timeout.DefaultSessionAwareExpirableDataManager.java

protected Map<String, DataHolder> createThreadSafeDataMap() {
    return new ConcurrentHashMap<>();
}

From source file:ch.algotrader.service.MarketDataCacheServiceImpl.java

public MarketDataCacheServiceImpl(final EngineManager engineManager, final LookupService lookupService,
        final Currency baseCurrency, final int lookBackDays) {

    Validate.notNull(engineManager, "EngineManager is null");
    Validate.notNull(lookupService, "LookupService is null");
    Validate.notNull(baseCurrency, "BaseCurrency is null");

    this.engineManager = engineManager;
    this.lookupService = lookupService;
    this.baseCurrency = baseCurrency;
    this.lookBackDays = lookBackDays;
    this.lastMarketDataEventBySecurityId = new ConcurrentHashMap<>();
    this.forexMap = new ConcurrentHashMap<>();
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.SaveAndSearchAndGetCallInConcurrentTest.java

@Test
public void test2SaveAndSearchAndGetCallIn(TestContext context) throws Exception {
    Async async = context.async();/*from   w  w w. j  a  v a 2  s .  co  m*/
    JsonNode source = JsonLoader.fromResource("/CallIn.json");
    int records = 1000;
    AtomicLong total = new AtomicLong(0);
    ConcurrentHashMap<JsonObject, String> m = new ConcurrentHashMap<>();
    Stream<JsonObject> stream = IntStream.rangeClosed(0, records).mapToObj(e -> {
        JsonObject clone = new JsonObject(Json.encode(source));
        Long number = Long.parseLong(clone.getString("phoneNumber")) + e;
        clone.put("phoneNumber", number + "");
        Long callTime = clone.getLong("callTime") + e;
        clone.put("callTime", callTime);
        return clone;
    });
    StopWatch sw = new StopWatch();
    sw.start();
    stream.parallel().forEach(e -> {
        org.simondean.vertx.async.Async.waterfall().<String>task(t -> {
            callInRepository.create(Json.encode(e), t);
        }).<List<CallIn>>task((id, t) -> {
            m.put(e, id);
            AtomicLong idc = new AtomicLong(0);
            org.simondean.vertx.async.Async.retry().<List<CallIn>>task(tt -> {
                callInRepository.searchIndexByScoreAndGet("callTime", e.getDouble("callTime"),
                        e.getDouble("callTime"), 0, 1, ttt -> {
                            logger.info("id = " + id + " | retry count: " + idc.incrementAndGet());
                            tt.handle(ttt.succeeded() && ttt.result() != null && !ttt.result().isEmpty()
                                    ? Future.succeededFuture(ttt.result())
                                    : Future.failedFuture(ttt.cause()));
                        });
            }).times(100000).run(t);
        }).run(r -> {
            context.assertTrue(r.succeeded());
            if (r.succeeded()) {
                context.assertFalse(r.result().isEmpty());
                context.assertEquals(1, r.result().size());
                CallIn ci = r.result().iterator().next();
                context.assertNotNull(ci);
                logger.info(Json.encode(ci));
                CallIn cii = Json.decodeValue(e.put("id", m.get(e)).encode(), CallIn.class);
                context.assertEquals(Json.encode(cii), Json.encode(ci));
            }
            long t;
            if ((t = total.incrementAndGet()) == records) {
                sw.stop();
                logger.info("time to concurrently save and search and get " + records + " call in records: "
                        + sw.getTime());
                async.complete();
            } else {
                logger.info("t = " + t);
            }
        });
    });

}

From source file:com.flexoodb.pool.ConnectionPool.java

public boolean set(String dbURL, String user, String password, String driverClassName, int initialConnections,
        int maxConnections, String s, boolean autoreturn) throws Exception {

    boolean success = false;

    try {/* w  w  w .  j a  va 2  s  .com*/

        if (_connected)
            disconnect();

        this.CTXT = s;

        //Class.forName(driverClassName).newInstance();
        this.dbURL = dbURL;
        this.user = user;
        this.password = password;
        this.driverClassName = driverClassName;
        this.initconnections = initialConnections;
        this.maxconnections = maxConnections;

        //connections = new HashedMap(this.initconnections);

        if (autoreturn) {
            _borrowed = new ConcurrentHashMap<Connection, Date>();
            _autoreturn = true;

            _checker = new Checker();
            (new Thread(_checker)).start();

        }

        // set timeout for 10 seconds.
        this.timeout = 300000;
        _connected = true;

        if (reconnect()) {
            success = true;
        } else {
            throw new Exception(
                    "Error: ConnectionPool could not be started, please check ODBC parameter settings or if the DB is accessible.");
        }

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

    return success;
}

From source file:ch.algotrader.cache.CacheManagerImpl.java

public CacheManagerImpl(GenericDao genericDao) {

    this.collectionHandler = new CollectionHandler(this);
    this.entityHandler = new EntityHandler(this);
    this.entityCache = new EntityCache();
    this.queryCache = new QueryCache();
    this.genericDao = genericDao;
    this.queryStringMap = new ConcurrentHashMap<>();
    this.discriminatorValueMap = new ConcurrentHashMap<>();
}

From source file:com.xiaomi.linden.cluster.ShardClient.java

public ShardClient(final ZkClient zkClient, final String zk, final String path,
        final LindenService.ServiceIface localClient, final int localPort, final int shardId) {
    this.zk = zk;
    this.path = path;
    this.localClient = localClient;
    this.shardId = shardId;
    this.localHostPort = String.format("%s:%s", CommonUtils.getLocalHost(), localPort);

    // if the path does not exist, create it.
    // the path may be created later, so the listener will not work
    // and the isAvailable will always be false.
    if (!zkClient.exists(path)) {
        zkClient.createPersistent(path, true);
    }//from   w w  w  .  j ava 2s.c  o  m

    List<String> children = zkClient.getChildren(path);
    final Map<String, Map.Entry<String, LindenService.ServiceIface>> lindenClients = new ConcurrentHashMap<>();
    zkClient.subscribeChildChanges(path, new LindenZKListener(path, children) {
        @Override
        public void onChildChange(String parent, List<String> children, List<String> newAdded,
                List<String> deleted) {
            for (String node : newAdded) {
                String fullPath = FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, node));
                byte[] bytes = zkClient.readData(fullPath);

                ServiceInstance instance = JSONObject.parseObject(new String(bytes), ServiceInstance.class);
                String hostPort = String.format("%s:%s", instance.getServiceEndpoint().getHost(),
                        instance.getServiceEndpoint().getPort());
                if (localHostPort.equals(hostPort)) {
                    haslocalClient = true;
                    lindenClients.put(node, new AbstractMap.SimpleEntry<>(hostPort, localClient));
                    LOGGER.info("Linden local node {} {} joined shard {}.", node, hostPort, shardId);
                } else {
                    LindenService.ServiceIface client = Thrift.newIface(hostPort,
                            LindenService.ServiceIface.class);
                    lindenClients.put(node, new AbstractMap.SimpleEntry<>(hostPort, client));
                    LOGGER.info("Linden node {} {} joined shard {}.", node, hostPort, shardId);
                }
            }
            for (String node : deleted) {
                if (lindenClients.containsKey(node)) {
                    String hostPort = lindenClients.get(node).getKey();
                    lindenClients.remove(node);
                    LOGGER.info("Linden node {} {} left shard {}.", node, hostPort, shardId);
                }
            }

            // ensure the new node overrides the old node.
            List<String> sortedNodes = new ArrayList<>();
            for (String node : lindenClients.keySet()) {
                sortedNodes.add(node);
            }
            Collections.sort(sortedNodes, Collections.reverseOrder());

            Set<String> uniqueClients = new HashSet<>();
            for (String node : sortedNodes) {
                String hostPort = lindenClients.get(node).getKey();
                if (uniqueClients.contains(hostPort)) {
                    lindenClients.remove(node);
                    LOGGER.warn("Linden node {} {} is duplicated in shard {}, removed!", node, hostPort,
                            shardId);
                } else {
                    uniqueClients.add(hostPort);
                }
            }

            LOGGER.info("{} Linden node in shard {}.", lindenClients.size(), shardId);
            List<Map.Entry<String, LindenService.ServiceIface>> tempClients = new ArrayList<>();
            for (String node : lindenClients.keySet()) {
                tempClients.add(lindenClients.get(node));
                String hostPort = lindenClients.get(node).getKey();
                LOGGER.info("Linden node {} {} on service in shard {}.", node, hostPort, shardId);
            }
            clients = tempClients;
        }
    });
}

From source file:epgtools.dumpepgfromts.FileLoader.java

public void load() throws FileNotFoundException {

    //??/*w w  w.j  av  a  2s.c o  m*/
    if (!tsFile.isFile()) {
        throw new FileNotFoundException(
                "???? = " + tsFile.getAbsolutePath());
    }

    //SDT?EIT?
    final Set<Integer> pids = new HashSet<>();
    pids.addAll(RESERVED_PROGRAM_ID.SDT_OR_BAT.getPids());
    pids.addAll(RESERVED_PROGRAM_ID.EIT_GR_ST.getPids());

    LOG.info("?? = " + tsFile.getAbsolutePath());
    final TsReader reader = new TsReader(tsFile, pids, limit);
    Map<Integer, List<TsPacketParcel>> pid_packets = reader.getPackets();

    Map<Integer, List<Section>> pids_sections_temp = new ConcurrentHashMap<>();
    for (Integer pidKey : pid_packets.keySet()) {
        LOG.info("?pid = " + Integer.toHexString(pidKey) + " pid = "
                + RESERVED_PROGRAM_ID.reverseLookUp(pidKey));
        SectionReconstructor sectionMaker = new SectionReconstructor(pid_packets.get(pidKey), pidKey);
        List<Section> sections = sectionMaker.getSections();
        if (sections != null) {
            LOG.info(" = " + sections.size());
            pids_sections_temp.put(pidKey, sections);
        }
    }
    Map<Integer, List<Section>> pids_sections = Collections.unmodifiableMap(pids_sections_temp);

    pid_packets = null;
    pids_sections_temp = null;

    ChannelDataExtractor chde = new ChannelDataExtractor();
    ProgrammeDataExtractor pgde = new ProgrammeDataExtractor();

    for (Integer pid : pids_sections.keySet()) {
        LOG.info("?pid = " + Integer.toHexString(pid) + " pid = "
                + RESERVED_PROGRAM_ID.reverseLookUp(pid));
        for (Section s : pids_sections.get(pid)) {
            try {
                if (RESERVED_PROGRAM_ID.reverseLookUp(pid) == RESERVED_PROGRAM_ID.SDT_OR_BAT) {
                    chde.makeDataSet(s);
                } else if (RESERVED_PROGRAM_ID.reverseLookUp(pid) == RESERVED_PROGRAM_ID.EIT_GR_ST) {
                    pgde.makeDataSet(s);
                }
            } catch (IllegalArgumentException ex) {
                LOG.warn(ex);
            }
        }
    }
    this.channels = chde.getUnmodifiableDataSet();
    this.programmes = pgde.getUnmodifiableDataSet();
}

From source file:com.mirth.connect.server.api.providers.MirthResourceInvocationHandlerProvider.java

@Override
public InvocationHandler create(Invocable method) {
    return new InvocationHandler() {
        @Override/*from   w  ww . j  a  v  a 2s.  co  m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String originalThreadName = Thread.currentThread().getName();

            try {
                if (proxy instanceof MirthServlet) {
                    try {
                        MirthServlet mirthServlet = (MirthServlet) proxy;

                        Map<Method, MethodInfo> methodMap = infoMap.get(proxy.getClass());
                        if (methodMap == null) {
                            methodMap = new ConcurrentHashMap<Method, MethodInfo>();
                            infoMap.put(mirthServlet.getClass(), methodMap);
                        }

                        MethodInfo methodInfo = methodMap.get(method);
                        if (methodInfo == null) {
                            methodInfo = new MethodInfo();
                            methodMap.put(method, methodInfo);
                        }

                        Operation operation = methodInfo.getOperation();
                        if (operation == null) {
                            /*
                             * Get the operation from the MirthOperation annotation present on
                             * the interface method.
                             */
                            Class<?> clazz = proxy.getClass();

                            while (clazz != null && operation == null) {
                                for (Class<?> interfaceClass : clazz.getInterfaces()) {
                                    if (BaseServletInterface.class.isAssignableFrom(interfaceClass)) {
                                        operation = OperationUtil.getOperation(interfaceClass, method);
                                        if (operation != null) {
                                            methodInfo.setOperation(operation);
                                            break;
                                        }
                                    }
                                }

                                clazz = clazz.getSuperclass();
                            }
                        }
                        mirthServlet.setOperation(operation);

                        // Set thread name based on the servlet class and operation name
                        Thread.currentThread().setName(mirthServlet.getClass().getSimpleName() + " Thread ("
                                + operation.getDisplayName() + ") < " + originalThreadName);

                        /*
                         * If a DontCheckAuthorized annotation is present on the server
                         * implementation method, then no auditing is done now and the servlet
                         * is expected to call checkUserAuthorized. Two other optional
                         * annotations determine whether the channel/user ID should be used in
                         * the authorization check.
                         */
                        Boolean checkAuthorized = methodInfo.getCheckAuthorized();
                        if (checkAuthorized == null) {
                            checkAuthorized = true;

                            Method matchingMethod = mirthServlet.getClass().getMethod(method.getName(),
                                    method.getParameterTypes());
                            if (matchingMethod != null) {
                                checkAuthorized = matchingMethod
                                        .getAnnotation(DontCheckAuthorized.class) == null;
                                methodInfo.setCheckAuthorizedChannelId(
                                        matchingMethod.getAnnotation(CheckAuthorizedChannelId.class));
                                methodInfo.setCheckAuthorizedUserId(
                                        matchingMethod.getAnnotation(CheckAuthorizedUserId.class));
                            }

                            methodInfo.setCheckAuthorized(checkAuthorized);
                        }

                        if (checkAuthorized) {
                            /*
                             * We need to know what parameter index the channel/user ID resides
                             * at so we can correctly include it with the authorization request.
                             */
                            Integer channelIdIndex = methodInfo.getChannelIdIndex();
                            Integer userIdIndex = methodInfo.getUserIdIndex();

                            if (args.length > 0) {
                                List<String> paramNames = methodInfo.getParamNames();
                                if (paramNames == null) {
                                    paramNames = new ArrayList<String>();
                                    List<Integer> notFoundIndicies = new ArrayList<Integer>();

                                    /*
                                     * The Param annotation lets us know at runtime the name to
                                     * use when adding entries into the parameter map, which
                                     * will eventually be stored in the event logs.
                                     */
                                    int count = 0;
                                    for (Annotation[] paramAnnotations : method.getParameterAnnotations()) {
                                        boolean found = false;
                                        for (Annotation annotation : paramAnnotations) {
                                            if (annotation instanceof Param) {
                                                Param param = (Param) annotation;
                                                // Set the name to null if we're not including it in the parameter map
                                                paramNames.add(param.excludeFromAudit() ? null : param.value());
                                                found = true;
                                                break;
                                            }
                                        }
                                        if (!found) {
                                            notFoundIndicies.add(count);
                                            paramNames.add(null);
                                        }
                                        count++;
                                    }

                                    // For each parameter name that wasn't found, replace it with a default name to use in the parameter map
                                    if (CollectionUtils.isNotEmpty(notFoundIndicies)) {
                                        for (Integer index : notFoundIndicies) {
                                            paramNames.set(index, getDefaultParamName(paramNames));
                                        }
                                    }

                                    methodInfo.setParamNames(paramNames);
                                }

                                // Add all arguments to the parameter map, except those that had excludeFromAudit enabled.
                                for (int i = 0; i < args.length; i++) {
                                    String paramName = paramNames.get(i);
                                    if (paramName != null) {
                                        mirthServlet.addToParameterMap(paramNames.get(i), args[i]);
                                    }
                                }

                                if (channelIdIndex == null) {
                                    channelIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedChannelId() != null) {
                                        channelIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedChannelId().paramName());
                                    }
                                    methodInfo.setChannelIdIndex(channelIdIndex);
                                }

                                if (userIdIndex == null) {
                                    userIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedUserId() != null) {
                                        userIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedUserId().paramName());
                                    }
                                    methodInfo.setUserIdIndex(userIdIndex);
                                }
                            }

                            // Authorize the request
                            if (channelIdIndex != null && channelIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((String) args[channelIdIndex]);
                            } else if (userIdIndex != null && userIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((Integer) args[userIdIndex],
                                        methodInfo.getCheckAuthorizedUserId().auditCurrentUser());
                            } else {
                                mirthServlet.checkUserAuthorized();
                            }
                        }
                    } catch (Throwable t) {
                        Throwable converted = convertThrowable(t, new HashSet<Throwable>());
                        if (converted != null) {
                            t = converted;
                        }

                        if (!(t instanceof WebApplicationException)) {
                            t = new MirthApiException(t);
                        }
                        throw new InvocationTargetException(t);
                    }
                }

                try {
                    return method.invoke(proxy, args);
                } catch (InvocationTargetException e) {
                    Throwable converted = convertThrowable(e, new HashSet<Throwable>());
                    if (converted != null && converted instanceof InvocationTargetException) {
                        e = (InvocationTargetException) converted;
                    }
                    throw e;
                }
            } finally {
                Thread.currentThread().setName(originalThreadName);
            }
        }
    };
}

From source file:com.mmnaseri.dragonfly.entity.impl.DefaultEntityHandlerContext.java

public DefaultEntityHandlerContext(EntityContext entityContext, TableMetadataRegistry tableMetadataRegistry) {
    this.entityContext = entityContext;
    this.tableMetadataRegistry = tableMetadataRegistry;
    if (entityContext instanceof DefaultEntityContext) {
        final DefaultEntityContext context = (DefaultEntityContext) entityContext;
        context.setHandlerContext(this);
    }//from   w ww.j av a2s .  c om
    try {
        defaultEntityCreator = new DefaultMapEntityCreator();
    } catch (RegistryException e) {
        throw new RuntimeException(e);
    }
    defaultMapCreator = new DefaultEntityMapCreator();
    entityCreators = new ConcurrentHashMap<Class<?>, MapEntityCreator>();
    mapCreators = new ConcurrentHashMap<Class<?>, EntityMapCreator>();
    entityHandlers = new ConcurrentHashMap<Class<?>, EntityHandler<?>>();
    log.info("Started entity handler context ...");
}

From source file:ai.grakn.engine.backgroundtasks.standalone.StandaloneTaskManager.java

private StandaloneTaskManager() {
    instantiatedTasks = new ConcurrentHashMap<>();
    stateStorage = InMemoryStateStorage.getInstance();
    stateUpdateLock = new ReentrantLock();

    ConfigProperties properties = ConfigProperties.getInstance();
    schedulingService = Executors.newScheduledThreadPool(1);
    executorService = Executors.newFixedThreadPool(properties.getAvailableThreads());
}