List of usage examples for java.util.concurrent ConcurrentHashMap put
public V put(K key, V value)
From source file:org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIEventAdapter.java
@Override public void init() throws OutputEventAdapterException { tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); //ExecutorService will be assigned if it is null if (executorService == null) { int minThread; int maxThread; long defaultKeepAliveTime; int jobQueSize; //If global properties are available those will be assigned else constant values will be assigned if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) { minThread = Integer//from w ww . jav a 2s. com .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME)); } else { minThread = UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) { maxThread = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME)); } else { maxThread = UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) { defaultKeepAliveTime = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME)); } else { defaultKeepAliveTime = UIEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) { jobQueSize = Integer.parseInt( globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME)); } else { jobQueSize = UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE; } executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(jobQueSize)); } streamId = eventAdapterConfiguration.getOutputStreamIdOfWso2eventMessageFormat(); if (streamId == null || streamId.isEmpty()) { throw new OutputEventAdapterRuntimeException("UI event adapter needs a output stream id"); } // fetch the "streamDefinition" corresponding to the "streamId" and then fetch the different attribute types // of the streamDefinition corresponding to the event's streamId. They are required when validating values in // the events against the streamDef attributes. StreamDefinition streamDefinition = getStreamDefinition(streamId); streamMetaAttributes = streamDefinition.getMetaData(); streamCorrelationAttributes = streamDefinition.getCorrelationData(); streamPayloadAttributes = streamDefinition.getPayloadData(); ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>> tenantSpecifcEventOutputAdapterMap = UIEventAdaptorServiceDataHolder .getTenantSpecificOutputEventStreamAdapterMap(); ConcurrentHashMap<String, String> streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId); if (streamSpecifAdapterMap == null) { streamSpecifAdapterMap = new ConcurrentHashMap<>(); if (null != tenantSpecifcEventOutputAdapterMap.putIfAbsent(tenantId, streamSpecifAdapterMap)) { streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId); } } String adapterName = streamSpecifAdapterMap.get(streamId); if (adapterName != null) { throw new OutputEventAdapterException(("An Output ui event adapter \"" + adapterName + "\" is already" + " exist for stream id \"" + streamId + "\"")); } else { streamSpecifAdapterMap.put(streamId, eventAdapterConfiguration.getName()); ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>> tenantSpecificStreamMap = UIEventAdaptorServiceDataHolder .getTenantSpecificStreamEventMap(); ConcurrentHashMap<String, LinkedBlockingDeque<Object>> streamSpecificEventsMap = tenantSpecificStreamMap .get(tenantId); if (streamSpecificEventsMap == null) { streamSpecificEventsMap = new ConcurrentHashMap<>(); if (null != tenantSpecificStreamMap.putIfAbsent(tenantId, streamSpecificEventsMap)) { streamSpecificEventsMap = tenantSpecificStreamMap.get(tenantId); } } streamSpecificEvents = streamSpecificEventsMap.get(streamId); if (streamSpecificEvents == null) { streamSpecificEvents = new LinkedBlockingDeque<>(); if (null != streamSpecificEventsMap.putIfAbsent(streamId, streamSpecificEvents)) { streamSpecificEvents = streamSpecificEventsMap.get(streamId); } } } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME) != null) { try { queueSize = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME)); } catch (NumberFormatException e) { log.error("String does not have the appropriate format for conversion." + e.getMessage()); queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; } } else { queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; } }
From source file:org.waarp.common.filemonitor.FileMonitor.java
/** * /*from w w w .j a va2 s. c o m*/ * @return the status (updated only) in JSON format */ public String getStatus() { Set<String> removedFileItems = null; ConcurrentHashMap<String, FileItem> newFileItems = new ConcurrentHashMap<String, FileMonitor.FileItem>(); if (!lastFileItems.isEmpty()) { removedFileItems = lastFileItems.keySet(); removedFileItems.removeAll(fileItems.keySet()); for (Entry<String, FileItem> key : fileItems.entrySet()) { if (!key.getValue().isStrictlySame(lastFileItems.get(key.getKey()))) { newFileItems.put(key.getKey(), key.getValue()); } } } else { for (Entry<String, FileItem> key : fileItems.entrySet()) { newFileItems.put(key.getKey(), key.getValue()); } } FileMonitorInformation fileMonitorInformation = new FileMonitorInformation(name, newFileItems, removedFileItems, directories, stopFile, statusFile, elapseTime, scanSubDir, globalok, globalerror, todayok, todayerror); for (Entry<String, FileItem> key : fileItems.entrySet()) { FileItem clone = key.getValue().clone(); lastFileItems.put(key.getKey(), clone); } createChkFile(); String status = JsonHandler.writeAsString(fileMonitorInformation); if (removedFileItems != null) { removedFileItems.clear(); } newFileItems.clear(); return status; }
From source file:org.sakaiproject.search.indexer.impl.test.SequenceGeneratorDisabled.java
/** * Test method for/*from w ww . ja va 2s . c om*/ * {@link org.sakaiproject.search.transaction.impl.TransactionSequenceImpl#getNextId()}. */ public final void testGetNextId() { log.info("================================== " + this.getClass().getName() + ".testGetNextId"); nt = 0; fail = 0; final ConcurrentHashMap<Long, Long> m = new ConcurrentHashMap<Long, Long>(); for (int i = 0; i < 20; i++) { Thread t = new Thread(new Runnable() { public void run() { try { nt++; long n = 0; Map<Long, Long> seq = new HashMap<Long, Long>(); for (int i = 0; i < 1000; i++) { n = sequenceGenerator.getNextId(); if (seq.get(n) != null) { fail = n; fail("Local clash on " + n); } seq.put(n, n); } log.debug("Last " + n); for (long nx : seq.values()) { if (m.get(nx) != null) { fail = nx; fail("Concurrent clash on " + nx); } m.put(nx, nx); } } finally { nt--; } } }); t.start(); } while (nt > 0) { if (fail != 0) { fail("Failed with clash on " + fail); } Thread.yield(); } log.info("==PASSED========================== " + this.getClass().getName() + ".testGetNextId"); }
From source file:org.rifidi.edge.configuration.ConfigurationServiceImpl.java
/** * Load the configuration. Not thread safe. * //from w w w.j a v a 2 s.c om * @return */ private ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> loadConfig() { ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> ret = new ConcurrentHashMap<String, Set<DefaultConfigurationImpl>>(); ConfigurationStore store; try { store = (ConfigurationStore) jaxbContext.createUnmarshaller().unmarshal(persistanceResource.getFile()); } catch (IOException e) { logger.error("Error loading config/rifidi.xml, no configuration loaded"); return ret; } catch (JAXBException e) { logger.error("Exception loading config/rifidi.xml or file not found, no configuration loaded"); return ret; } if (store.getServices() != null) { for (ServiceStore service : store.getServices()) { if (ret.get(service.getFactoryID()) == null) { ret.put(service.getFactoryID(), new CopyOnWriteArraySet<DefaultConfigurationImpl>()); } AttributeList attributes = new AttributeList(); // get all properties for (String key : service.getAttributes().keySet()) { // factoryid is already processed if (Constants.FACTORYID.equals(key)) { continue; } // type is already processed if (Constants.FACTORY_TYPE.equals(key)) { continue; } attributes.add(new Attribute(key, service.getAttributes().get(key))); } if (!checkName(service.getServiceID())) { continue; } ret.get(service.getFactoryID()).add(createAndRegisterConfiguration(service.getServiceID(), service.getFactoryID(), attributes, service.getSessionDTOs())); serviceNames.add(service.getServiceID()); } } return ret; }
From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java
/** * Get a JAXBContext for the class//ww w. jav a 2 s .com * * Note: The contextPackage object is used by multiple threads. It should be considered immutable * and not altered by this method. * * @param contextPackage Set<Package> * @param contructionType (output value that indicates how the context was constructed) * @param forceArrays (forces the returned JAXBContext to include the array types) * @param cacheKey ClassLoader * @return JAXBContext * @throws JAXBException */ public static JAXBContext getJAXBContext(TreeSet<String> contextPackages, Holder<CONSTRUCTION_TYPE> constructionType, boolean forceArrays, String key, ClassLoader cacheKey, Map<String, ?> properties) throws JAXBException { // JAXBContexts for the same class can be reused and are supposed to be thread-safe if (log.isDebugEnabled()) { log.debug("Following packages are in this batch of getJAXBContext() :"); for (String pkg : contextPackages) { log.debug(pkg); } } if (JAXBUtilsMonitor.isMonitoring()) { JAXBUtilsMonitor.addPackageKey(contextPackages.toString()); } // Get or Create The InnerMap using the package key ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null; SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key); if (softRef != null) { innerMap = softRef.get(); } if (innerMap == null) { synchronized (jaxbMap) { softRef = jaxbMap.get(key); if (softRef != null) { innerMap = softRef.get(); } if (innerMap == null) { innerMap = new ConcurrentHashMap<ClassLoader, JAXBContextValue>(); softRef = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(innerMap); jaxbMap.put(key, softRef); } } } // Now get the contextValue using either the classloader key or // the current Classloader ClassLoader cl = getContextClassLoader(); JAXBContextValue contextValue = null; if (cacheKey != null) { if (log.isDebugEnabled()) { log.debug("Using supplied classloader to retrieve JAXBContext: " + cacheKey); } contextValue = innerMap.get(cacheKey); } else { if (log.isDebugEnabled()) { log.debug("Using classloader from Thread to retrieve JAXBContext: " + cl); } contextValue = innerMap.get(cl); } // If the context value is found, but the caller requested that the JAXBContext // contain arrays, then rebuild the JAXBContext value if (forceArrays && contextValue != null && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) { if (log.isDebugEnabled()) { log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType + " but the caller requested a JAXBContext " + " that includes arrays. A new JAXBContext will be built"); } contextValue = null; } if (contextPackages == null) { contextPackages = new TreeSet<String>(); } if (contextValue == null) { synchronized (innerMap) { // Try to get the contextValue once more since sync was temporarily exited. ClassLoader clKey = (cacheKey != null) ? cacheKey : cl; contextValue = innerMap.get(clKey); adjustPoolSize(innerMap); if (forceArrays && contextValue != null && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) { contextValue = null; } if (contextValue == null) { // Create a copy of the contextPackages. This new TreeSet will // contain only the valid contextPackages. // Note: The original contextPackage set is accessed by multiple // threads and should not be altered. TreeSet<String> validContextPackages = new TreeSet<String>(contextPackages); List<String> classRefs = pruneDirectives(validContextPackages); int numPackages = validContextPackages.size(); contextValue = createJAXBContextValue(validContextPackages, clKey, forceArrays, properties, classRefs); synchronized (jaxbMap) { // Add the context value with the original package set ConcurrentHashMap<ClassLoader, JAXBContextValue> map1 = null; SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef1 = jaxbMap.get(key); if (softRef1 != null) { map1 = softRef1.get(); } if (map1 == null) { map1 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>(); softRef1 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map1); jaxbMap.put(key, softRef1); } map1.put(clKey, contextValue); String validPackagesKey = validContextPackages.toString(); // Add the context value with the new package set ConcurrentHashMap<ClassLoader, JAXBContextValue> map2 = null; SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef2 = jaxbMap .get(validPackagesKey); if (softRef2 != null) { map2 = softRef2.get(); } if (map2 == null) { map2 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>(); softRef2 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map2); jaxbMap.put(validPackagesKey, softRef2); } map2.put(clKey, contextValue); if (log.isDebugEnabled()) { log.debug("JAXBContext [created] for " + key); log.debug("JAXBContext also stored by the list of valid packages:" + validPackagesKey); } } } } } else { if (log.isDebugEnabled()) { log.debug("JAXBContext [from pool] for " + key); } } if (log.isDebugEnabled()) { log.debug("JAXBContext constructionType= " + contextValue.constructionType); log.debug("JAXBContextValue = " + JavaUtils.getObjectIdentity(contextValue)); log.debug("JAXBContext = " + JavaUtils.getObjectIdentity(contextValue.jaxbContext)); } constructionType.value = contextValue.constructionType; return contextValue.jaxbContext; }
From source file:org.seedstack.mqtt.internal.MqttPluginTest.java
/** * Test method for {@link org.seedstack.mqtt.internal.MqttPlugin#stop()}. * /* w w w . j a va 2 s .c o m*/ * @throws Exception * if an error occurred */ @SuppressWarnings("static-access") @Test(expected = SeedException.class) public void testStartConnectWithSecurityException(@Mocked final IMqttClient mqttClient, @Mocked final Configuration configuration, @Mocked final Context context, @Mocked final MqttClientUtils mqttClientUtils) throws Exception { MqttPlugin plugin = new MqttPlugin(); ConcurrentHashMap<String, IMqttClient> clients = new ConcurrentHashMap<String, IMqttClient>(); final String client1 = "clients"; clients.put(client1, mqttClient); Deencapsulation.setField(plugin, "mqttClients", clients); ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); final MqttClientDefinition clientDefinition = new MqttClientDefinition("xx", "id"); mqttClientDefinitions.put(client1, clientDefinition); Deencapsulation.setField(plugin, "mqttClientDefinitions", mqttClientDefinitions); new Expectations() { { mqttClientUtils.connect(mqttClient, clientDefinition); result = new MqttSecurityException(MqttException.REASON_CODE_BROKER_UNAVAILABLE); } }; plugin.start(context); }
From source file:org.seedstack.mqtt.internal.MqttPluginTest.java
/** * Test method for {@link org.seedstack.mqtt.internal.MqttPlugin#stop()}. * //from ww w. j ava2 s .com * @throws Exception * if an error occurred */ @SuppressWarnings("static-access") @Test(expected = SeedException.class) public void testStartConnectWithException(@Mocked final IMqttClient mqttClient, @Mocked final Configuration configuration, @Mocked final Context context, @Mocked final MqttClientUtils mqttClientUtils) throws Exception { MqttPlugin plugin = new MqttPlugin(); ConcurrentHashMap<String, IMqttClient> clients = new ConcurrentHashMap<String, IMqttClient>(); final String client1 = "clients"; clients.put(client1, mqttClient); Deencapsulation.setField(plugin, "mqttClients", clients); ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); final MqttClientDefinition clientDefinition = new MqttClientDefinition("xx", "id"); mqttClientDefinitions.put(client1, clientDefinition); Deencapsulation.setField(plugin, "mqttClientDefinitions", mqttClientDefinitions); new Expectations() { { mqttClientUtils.connect(mqttClient, clientDefinition); result = new MqttException(MqttException.REASON_CODE_BROKER_UNAVAILABLE); } }; plugin.start(context); }
From source file:org.seedstack.mqtt.internal.MqttPluginTest.java
/** * Test method for {@link org.seedstack.mqtt.internal.MqttPlugin#stop()}. * //from www . jav a2 s . c om * @throws Exception * if an error occurred */ @SuppressWarnings("static-access") @Test public void testStartWithoutListener(@Mocked final IMqttClient mqttClient, @Mocked final Configuration configuration, @Mocked final Context context, @Mocked final MqttClientUtils mqttClientUtils) throws Exception { MqttPlugin plugin = new MqttPlugin(); ConcurrentHashMap<String, IMqttClient> clients = new ConcurrentHashMap<String, IMqttClient>(); final String client1 = "clients"; clients.put(client1, mqttClient); Deencapsulation.setField(plugin, "mqttClients", clients); ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); final MqttClientDefinition clientDefinition = new MqttClientDefinition("xx", "id"); mqttClientDefinitions.put(client1, clientDefinition); Deencapsulation.setField(plugin, "mqttClientDefinitions", mqttClientDefinitions); plugin.start(context); new Verifications() { { mqttClientUtils.connect(mqttClient, clientDefinition); } }; }
From source file:org.seedstack.mqtt.internal.MqttPluginTest.java
/** * Test method for {@link org.seedstack.mqtt.internal.MqttPlugin#stop()}. * // w w w .ja v a 2 s . c o m * @throws Exception * if an error occurred */ @SuppressWarnings("static-access") @Test public void testStart(@Mocked final IMqttClient mqttClient, @Mocked final Configuration configuration, @Mocked final Context context, @Mocked final MqttClientUtils mqttClientUtils) throws Exception { MqttPlugin plugin = new MqttPlugin(); ConcurrentHashMap<String, IMqttClient> clients = new ConcurrentHashMap<String, IMqttClient>(); final String client1 = "clients"; clients.put(client1, mqttClient); Deencapsulation.setField(plugin, "mqttClients", clients); ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); // clients 1 with listener final MqttClientDefinition clientDefinition = new MqttClientDefinition("xx", "id"); final MqttListenerDefinition listenerDefinition = new MqttListenerDefinition(Listener1.class, Listener1.class.getCanonicalName(), new String[] { "topic" }, new int[] { 0 }); clientDefinition.setListenerDefinition(listenerDefinition); mqttClientDefinitions.put(client1, clientDefinition); Deencapsulation.setField(plugin, "mqttClientDefinitions", mqttClientDefinitions); plugin.start(context); new Verifications() { { mqttClientUtils.connect(mqttClient, clientDefinition); mqttClientUtils.subscribe(mqttClient, listenerDefinition); } }; }
From source file:org.seedstack.mqtt.internal.MqttPluginTest.java
/** * Test method for {@link org.seedstack.mqtt.internal.MqttPlugin#stop()}. * //from ww w. j a v a 2 s . com * @throws Exception * if an error occurred */ @SuppressWarnings("static-access") @Test(expected = SeedException.class) public void testStartWithListenerException(@Mocked final IMqttClient mqttClient, @Mocked final Configuration configuration, @Mocked final Context context, @Mocked final MqttClientUtils mqttClientUtils) throws Exception { MqttPlugin plugin = new MqttPlugin(); ConcurrentHashMap<String, IMqttClient> clients = new ConcurrentHashMap<String, IMqttClient>(); final String client1 = "clients"; clients.put(client1, mqttClient); Deencapsulation.setField(plugin, "mqttClients", clients); ConcurrentHashMap<String, MqttClientDefinition> mqttClientDefinitions = new ConcurrentHashMap<String, MqttClientDefinition>(); // clients 1 with listener final MqttClientDefinition clientDefinition = new MqttClientDefinition("xx", "id"); final MqttListenerDefinition listenerDefinition = new MqttListenerDefinition(Listener1.class, Listener1.class.getCanonicalName(), new String[] { "topic" }, new int[] { 0 }); clientDefinition.setListenerDefinition(listenerDefinition); mqttClientDefinitions.put(client1, clientDefinition); Deencapsulation.setField(plugin, "mqttClientDefinitions", mqttClientDefinitions); new Expectations() { { mqttClientUtils.subscribe(mqttClient, listenerDefinition); result = new MqttException(MqttException.REASON_CODE_BROKER_UNAVAILABLE); } }; plugin.start(context); new Verifications() { { mqttClientUtils.connect(mqttClient, clientDefinition); } }; }