Java Code Examples for java.util.concurrent.ConcurrentMap
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.
Source file: TestStatementCache.java

/** * Tests statement cache clear. * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ @SuppressWarnings({"unchecked","rawtypes"}) @Test public void testStatementCacheClear() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, SQLException { ConcurrentMap mockCache=createNiceMock(ConcurrentMap.class); List<StatementHandle> mockStatementCollections=createNiceMock(List.class); StatementCache testClass=new StatementCache(1,false,null); Field field=testClass.getClass().getDeclaredField("cache"); field.setAccessible(true); field.set(testClass,mockCache); Iterator<StatementHandle> mockIterator=createNiceMock(Iterator.class); StatementHandle mockStatement=createNiceMock(StatementHandle.class); expect(mockCache.values()).andReturn(mockStatementCollections).anyTimes(); expect(mockStatementCollections.iterator()).andReturn(mockIterator).anyTimes(); expect(mockIterator.hasNext()).andReturn(true).times(2).andReturn(false).once(); expect(mockIterator.next()).andReturn(mockStatement).anyTimes(); mockStatement.close(); expectLastCall().once().andThrow(new SQLException()).once(); mockCache.clear(); expectLastCall().once(); replay(mockCache,mockStatementCollections,mockIterator,mockStatement); testClass.clear(); verify(mockCache,mockStatement); }
Example 2
From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/testing/.
Source file: ConfigAssertions.java

public static <T>T recordDefaults(Class<T> type){ final T instance=newDefaultInstance(type); T proxy=(T)Enhancer.create(type,new Class[]{$$RecordingConfigProxy.class},new MethodInterceptor(){ private final ConcurrentMap<Method,Object> invokedMethods=new MapMaker().makeMap(); @Override public Object intercept( Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if (GET_RECORDING_CONFIG_METHOD.equals(method)) { return new $$RecordedConfigData<T>(instance,ImmutableSet.copyOf(invokedMethods.keySet())); } invokedMethods.put(method,Boolean.TRUE); Object result=methodProxy.invoke(instance,args); if (result == instance) { return proxy; } else { return result; } } } ); return proxy; }
Example 3
From project amplafi-sworddance, under directory /src/main/java/com/sworddance/beans/.
Source file: BeanWorker.java

/** * Each class has its own version of the PropertyMethodChain map. * @param clazz * @return PropertyMethodChain map for the passed class. */ protected ConcurrentMap<String,PropertyMethodChain> getMethodMap(Class<?> clazz){ ConcurrentMap<String,PropertyMethodChain> propMap; if (!methodsMap.containsKey(clazz)) { propMap=new ConcurrentHashMap<String,PropertyMethodChain>(); for ( String property : NotNullIterator.<String>newNotNullIterator(getPropertyNames())) { addPropertyMethodChainIfAbsent(clazz,propMap,property,false); } methodsMap.putIfAbsent(clazz,propMap); } propMap=methodsMap.get(clazz); return propMap; }
Example 4
From project android_external_guava, under directory /src/com/google/common/collect/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 5
From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/data/.
Source file: RecordBuilderBase.java

/** * Gets the default value of the given field, if any. * @param field the field whose default value should be retrieved. * @return the default value associated with the given field, or null if none is specified in the schema. * @throws IOException */ @SuppressWarnings({"rawtypes","unchecked"}) protected Object defaultValue(Field field) throws IOException { JsonNode defaultJsonValue=field.defaultValue(); if (defaultJsonValue == null) { throw new AvroRuntimeException("Field " + field + " not set and has no default value"); } if (defaultJsonValue.isNull() && (field.schema().getType() == Type.NULL || (field.schema().getType() == Type.UNION && field.schema().getTypes().get(0).getType() == Type.NULL))) { return null; } Object defaultValue=null; ConcurrentMap<Integer,Object> defaultSchemaValues=DEFAULT_VALUE_CACHE.get(schema.getFullName()); if (defaultSchemaValues == null) { DEFAULT_VALUE_CACHE.putIfAbsent(schema.getFullName(),new ConcurrentHashMap<Integer,Object>(fields.length)); defaultSchemaValues=DEFAULT_VALUE_CACHE.get(schema.getFullName()); } defaultValue=defaultSchemaValues.get(field.pos()); if (defaultValue == null) { ByteArrayOutputStream baos=new ByteArrayOutputStream(); encoder=EncoderFactory.get().binaryEncoder(baos,encoder); ResolvingGrammarGenerator.encode(encoder,field.schema(),defaultJsonValue); encoder.flush(); decoder=DecoderFactory.get().binaryDecoder(baos.toByteArray(),decoder); defaultValue=data.createDatumReader(field.schema()).read(null,decoder); defaultSchemaValues.putIfAbsent(field.pos(),defaultValue); } return data.deepCopy(field.schema(),defaultValue); }
Example 6
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/.
Source file: MapRecipe.java

public static Class getMap(Class type){ if (ReflectionUtils.hasDefaultConstructor(type)) { return type; } else if (SortedMap.class.isAssignableFrom(type)) { return TreeMap.class; } else if (ConcurrentMap.class.isAssignableFrom(type)) { return ConcurrentHashMap.class; } else { return LinkedHashMap.class; } }
Example 7
From project caseconductor-platform, under directory /utest-domain-model/src/main/java/com/utest/domain/util/.
Source file: DomainUtil.java

/** * Filter child data by corresponding parent * @param allData_ * @return */ public static ConcurrentMap<String,Vector<CodeValueEntity>> filterDataByParent(final Collection<ParentDependable> allData_){ final ConcurrentMap<String,Vector<CodeValueEntity>> filteredData=new ConcurrentHashMap<String,Vector<CodeValueEntity>>(); for ( final ParentDependable child : allData_) { final String parentId=child.getParentId() + ""; Vector<CodeValueEntity> parentData=filteredData.get(parentId); if (parentData == null) { parentData=new Vector<CodeValueEntity>(); filteredData.put(parentId,parentData); } parentData.add(DomainUtil.convertToCodeValue(child)); } return filteredData; }
Example 8
From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/impl/.
Source file: AbstractOpenNode.java

protected OpenNode put(ConcurrentMap<String,OpenNode> map,String label,OpenNode child){ final OpenNode previous=map.putIfAbsent(label,child); if (previous == null) { if (child instanceof AbstractOpenNode) { final AbstractOpenNode dn=(AbstractOpenNode)child; dn.parents.put(getLabel(),this); } } else { child=previous; } return child; }
Example 9
From project chromattic, under directory /common/src/main/java/org/chromattic/common/collection/.
Source file: Collections.java

public static <K,V>V putIfAbsent(ConcurrentMap<K,V> map,K key,V value){ V previous=map.putIfAbsent(key,value); if (previous == null) { return value; } else { return previous; } }
Example 10
From project DirectMemory, under directory /DirectMemory-Cache/src/main/java/org/apache/directmemory/cache/.
Source file: CacheServiceImpl.java

/** * Constructor */ public CacheServiceImpl(ConcurrentMap<K,Pointer<V>> map,MemoryManagerService<V> memoryManager,Serializer serializer){ checkArgument(map != null,"Impossible to initialize the CacheService with a null map"); checkArgument(memoryManager != null,"Impossible to initialize the CacheService with a null memoryManager"); checkArgument(serializer != null,"Impossible to initialize the CacheService with a null serializer"); this.map=map; this.memoryManager=memoryManager; this.serializer=serializer; }
Example 11
From project droid-fu, under directory /src/main/java/com/google/common/collect/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 12
From project enterprise, under directory /consistency-check/src/main/java/org/neo4j/consistency/checking/full/.
Source file: OwnerCheck.java

private static Map<RecordType,ConcurrentMap<Long,DynamicOwner>> initialize(DynamicStore[] stores){ EnumMap<RecordType,ConcurrentMap<Long,DynamicOwner>> map=new EnumMap<RecordType,ConcurrentMap<Long,DynamicOwner>>(RecordType.class); for ( DynamicStore store : stores) { map.put(store.type,new ConcurrentHashMap<Long,DynamicOwner>(16,0.75f,4)); } return unmodifiableMap(map); }
Example 13
From project fakereplace, under directory /core/src/main/java/org/fakereplace/manip/util/.
Source file: ManipulationDataStore.java

public Map<String,Set<T>> getManipulationData(ClassLoader loader){ if (loader == null) { loader=NULL_CLASS_LOADER; } Map<String,Set<T>> ret=new HashMap<String,Set<T>>(); for ( Entry<ClassLoader,ConcurrentMap<String,Set<T>>> centry : cldata.entrySet()) { for ( Entry<String,Set<T>> e : centry.getValue().entrySet()) { Set<T> set=new HashSet<T>(); ret.put(e.getKey(),set); for ( ClassLoaderFiltered<T> f : e.getValue()) { if (includeClassLoader(loader,f.getClassLoader())) { set.add(f.getInstance()); } } } } return ret; }
Example 14
From project fastjson, under directory /src/test/java/com/alibaba/json/bvt/parser/deser/.
Source file: DefaultObjectDeserializerTest2.java

public void test_3() throws Exception { String input="{'map':{}}"; DefaultExtJSONParser parser=new DefaultExtJSONParser(input,ParserConfig.getGlobalInstance(),JSON.DEFAULT_PARSER_FEATURE); DefaultObjectDeserializer deser=new DefaultObjectDeserializer(); SortedMap<String,ConcurrentMap> map=JSON.parseObject(input,new TypeReference<SortedMap<String,ConcurrentMap>>(){ } .getType()); Assert.assertEquals(ConcurrentHashMap.class,map.get("map").getClass()); }
Example 15
From project FlipDroid, under directory /web-image-view/src/main/java/com/goal98/android/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 16
From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/source/.
Source file: MultiportSyslogTCPSource.java

public MultiportSyslogHandler(int maxEventSize,int batchSize,ChannelProcessor cp,SourceCounter ctr,String portHeader,ThreadSafeDecoder defaultDecoder,ConcurrentMap<Integer,ThreadSafeDecoder> portCharsets){ channelProcessor=cp; sourceCounter=ctr; this.maxEventSize=maxEventSize; this.batchSize=batchSize; this.portHeader=portHeader; this.defaultDecoder=defaultDecoder; this.portCharsets=portCharsets; syslogParser=new SyslogParser(); lineSplitter=new LineSplitter(maxEventSize); }
Example 17
From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.
Source file: Cache.java

private ConcurrentMap<Long,CacheLine> buildSharedCache(long maxCapacity){ return new ConcurrentLinkedHashMap.Builder<Long,CacheLine>().initialCapacity(1000).maximumWeightedCapacity(maxCapacity).weigher(new Weigher<CacheLine>(){ @Override public int weightOf( CacheLine line){ return 1 + line.size(); } } ).listener(new EvictionListener<Long,CacheLine>(){ @Override public void onEviction( Long id, CacheLine line){ evictLine(line,true); } } ).build(); }
Example 18
From project gatein-toolbox, under directory /sqlman/src/main/java/org/sqlman/.
Source file: ConcurrentStatisticCollector.java

private ConcurrentMap<Integer,Statistic> safeGetMap(String kind){ ConcurrentMap<Integer,Statistic> tmp=state.get(kind); if (tmp == null) { tmp=config.buildMap(); ConcurrentMap<Integer,Statistic> phantom=state.putIfAbsent(kind,tmp); if (phantom != null) { tmp=phantom; } } return tmp; }
Example 19
From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/blueprint/container/support/.
Source file: BlueprintEditorRegistrar.java

public void registerCustomEditors(PropertyEditorRegistry registry){ registry.registerCustomEditor(Date.class,new DateEditor()); registry.registerCustomEditor(Stack.class,new BlueprintCustomCollectionEditor(Stack.class)); registry.registerCustomEditor(Vector.class,new BlueprintCustomCollectionEditor(Vector.class)); registry.registerCustomEditor(Collection.class,new BlueprintCustomCollectionEditor(Collection.class)); registry.registerCustomEditor(Set.class,new BlueprintCustomCollectionEditor(Set.class)); registry.registerCustomEditor(SortedSet.class,new BlueprintCustomCollectionEditor(SortedSet.class)); registry.registerCustomEditor(List.class,new BlueprintCustomCollectionEditor(List.class)); registry.registerCustomEditor(SortedMap.class,new CustomMapEditor(SortedMap.class)); registry.registerCustomEditor(HashSet.class,new BlueprintCustomCollectionEditor(HashSet.class)); registry.registerCustomEditor(LinkedHashSet.class,new BlueprintCustomCollectionEditor(LinkedHashSet.class)); registry.registerCustomEditor(TreeSet.class,new BlueprintCustomCollectionEditor(TreeSet.class)); registry.registerCustomEditor(ArrayList.class,new BlueprintCustomCollectionEditor(ArrayList.class)); registry.registerCustomEditor(LinkedList.class,new BlueprintCustomCollectionEditor(LinkedList.class)); registry.registerCustomEditor(HashMap.class,new CustomMapEditor(HashMap.class)); registry.registerCustomEditor(LinkedHashMap.class,new CustomMapEditor(LinkedHashMap.class)); registry.registerCustomEditor(Hashtable.class,new CustomMapEditor(Hashtable.class)); registry.registerCustomEditor(TreeMap.class,new CustomMapEditor(TreeMap.class)); registry.registerCustomEditor(Properties.class,new PropertiesEditor()); registry.registerCustomEditor(ConcurrentMap.class,new CustomMapEditor(ConcurrentHashMap.class)); registry.registerCustomEditor(ConcurrentHashMap.class,new CustomMapEditor(ConcurrentHashMap.class)); registry.registerCustomEditor(Queue.class,new BlueprintCustomCollectionEditor(LinkedList.class)); registry.registerCustomEditor(Dictionary.class,new CustomMapEditor(Hashtable.class)); }
Example 20
From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.core/src/test/java/org/eclipse/gemini/web/internal/.
Source file: WebApplicationStartFailureRetryControllerTests.java

@Test public void testRecordFailureNoContextPath() throws Exception { expect(this.servletContext.getContextPath()).andReturn(null); WebApplicationStartFailureRetryController webApplicationStartFailureRetryController=createWebApplicationStartFailureRetryController(); webApplicationStartFailureRetryController.recordFailure(createStandardWebApplication(this.bundle1,webApplicationStartFailureRetryController)); Field field=webApplicationStartFailureRetryController.getClass().getDeclaredField(FIELD_NAME); field.setAccessible(true); assertTrue(((ConcurrentMap<?,?>)field.get(webApplicationStartFailureRetryController)).size() == 0); field.setAccessible(false); }
Example 21
From project generic-store-for-android, under directory /src/com/google/common/collect/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 22
From project geronimo-xbean, under directory /xbean-reflect/src/main/java/org/apache/xbean/recipe/.
Source file: MapRecipe.java

public MapRecipe(Map<?,?> map){ if (map == null) throw new NullPointerException("map is null"); entries=new ArrayList<Object[]>(map.size()); if (RecipeHelper.hasDefaultConstructor(map.getClass())) { this.typeClass=map.getClass(); } else if (map instanceof SortedMap) { this.typeClass=TreeMap.class; } else if (map instanceof ConcurrentMap) { this.typeClass=ConcurrentHashMap.class; } else { this.typeClass=LinkedHashMap.class; } putAll(map); }
Example 23
From project giraph, under directory /src/main/java/org/apache/giraph/comm/messages/.
Source file: SimpleMessageStore.java

@Override public void addVertexMessages(I vertexId,Collection<M> messages) throws IOException { int partitionId=getPartitionId(vertexId); ConcurrentMap<I,Collection<M>> partitionMap=map.get(partitionId); if (partitionMap == null) { ConcurrentMap<I,Collection<M>> tmpMap=new MapMaker().concurrencyLevel(config.getNettyServerExecutionConcurrency()).makeMap(); partitionMap=map.putIfAbsent(partitionId,tmpMap); if (partitionMap == null) { partitionMap=map.get(partitionId); } } Collection<M> currentMessages=CollectionUtils.addConcurrent(vertexId,messages,partitionMap); if (combiner != null) { synchronized (currentMessages) { currentMessages=Lists.newArrayList(combiner.combine(vertexId,currentMessages)); partitionMap.put(vertexId,currentMessages); } } }
Example 24
From project griffon, under directory /subprojects/griffon-shell/src/main/groovy/org/apache/felix/gogo/commands/converter/.
Source file: GriffonDefaultConverter.java

private static Class getMap(Class type){ if (hasDefaultConstructor(type)) { return type; } else if (SortedMap.class.isAssignableFrom(type)) { return TreeMap.class; } else if (ConcurrentMap.class.isAssignableFrom(type)) { return ConcurrentHashMap.class; } else { return LinkedHashMap.class; } }
Example 25
From project hama, under directory /core/src/main/java/org/apache/hama/monitor/.
Source file: Monitor.java

/** * Load jar from plugin directory for executing task. */ public void run(){ try { while (!Thread.currentThread().interrupted()) { Map<String,Task> tasks=Configurator.configure((HamaConfiguration)this.conf,listener); if (null != tasks) { for ( Map.Entry<String,Task> entry : tasks.entrySet()) { String jarPath=entry.getKey(); Task t=entry.getValue(); TaskWorker old=(TaskWorker)((ConcurrentMap)this.workers).putIfAbsent(jarPath,new TaskWorker(t)); if (null != old) { ((ConcurrentMap)this.workers).replace(jarPath,new TaskWorker(t)); } } } LOG.debug("Task worker list's size: " + workers.size()); int period=conf.getInt("bsp.monitor.initializer.period",5); Thread.sleep(period * 1000); } } catch ( InterruptedException ie) { LOG.warn(this.getClass().getSimpleName() + " is interrupted.",ie); Thread.currentThread().interrupt(); } catch ( IOException ioe) { LOG.warn(this.getClass().getSimpleName() + " can not load jar file " + " from plugin directory.",ioe); Thread.currentThread().interrupt(); } }
Example 26
From project hawtjournal, under directory /src/main/java/org/fusesource/hawtjournal/api/.
Source file: DataFileAccessor.java

void dispose(DataFile dataFile){ for ( Entry<Thread,ConcurrentMap<Integer,RandomAccessFile>> threadRafs : perThreadDataFileRafs.entrySet()) { for ( Entry<Integer,RandomAccessFile> raf : threadRafs.getValue().entrySet()) { if (raf.getKey().equals(dataFile.getDataFileId())) { Lock lock=getOrCreateLock(threadRafs.getKey(),raf.getKey()); lock.lock(); try { removeRaf(threadRafs.getKey(),raf.getKey()); return; } catch ( IOException ex) { warn(ex,ex.getMessage()); } finally { lock.unlock(); } } } } }
Example 27
From project hcatalog, under directory /src/java/org/apache/hcatalog/common/.
Source file: HiveClientCache.java

/** * Note: This doesn't check if they are being used or not, meant only to be called during shutdown etc. */ void closeAllClientsQuietly(){ try { ConcurrentMap<HiveClientCacheKey,CacheableHiveMetaStoreClient> elements=hiveCache.asMap(); for ( CacheableHiveMetaStoreClient cacheableHiveMetaStoreClient : elements.values()) { cacheableHiveMetaStoreClient.tearDown(); } } catch ( Exception e) { LOG.warn("Clean up of hive clients in the cache failed. Ignored",e); } }
Example 28
From project heritrix3, under directory /commons/src/main/java/org/archive/io/warc/.
Source file: WARCWriter.java

public static long getStat(ConcurrentMap<String,ConcurrentMap<String,AtomicLong>> map,String key,String subkey){ if (map != null && map.get(key) != null && map.get(key).get(subkey) != null) { return map.get(key).get(subkey).get(); } else { return 0l; } }
Example 29
From project hibernate-dsc, under directory /src/main/java/com/corundumstudio/hibernate/dsc/.
Source file: QueryCacheEntityListener.java

public <T>void register(Class<T> clazz,String regionName,CacheCallback<T> handler){ ConcurrentMap<String,QueryListenerEntry> values=map.get(clazz); if (values == null) { values=new ConcurrentHashMap<String,QueryListenerEntry>(); ConcurrentMap<String,QueryListenerEntry> oldValues=map.putIfAbsent(clazz,values); if (oldValues != null) { values=oldValues; } } QueryListenerEntry entry=values.get(regionName); if (entry == null) { entry=new QueryListenerEntry(regionName,handler); values.putIfAbsent(regionName,entry); } }
Example 30
From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/index/.
Source file: BasicPromoter.java

/** * Constructor. Creates an empty Promoter. * @param backupDir the directory to wich the data stored in this Scorer shall be * @param load if true, the promoter is generated from it's serialized version.persisted. */ @SuppressWarnings("unchecked") public BasicPromoter(File backupDir,boolean load) throws IOException { checkDirArgument(backupDir); this.backupDir=backupDir; if (!load) { storage=new ConcurrentHashMap<String,String>(); } else { File f=new File(this.backupDir,MAIN_FILE_NAME); ObjectInputStream is=null; try { is=new ObjectInputStream(new BufferedInputStream(new FileInputStream(f))); try { storage=(ConcurrentMap<String,String>)is.readObject(); } catch ( ClassNotFoundException e) { throw new IllegalStateException(e); } } finally { Execute.close(is); } } }
Example 31
From project ioke, under directory /src/ikj/main/com/google/common/collect/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 32
From project Ivory, under directory /prism/src/main/java/org/apache/ivory/service/.
Source file: SLAMonitoringService.java

private void removeFromPendingList(Entity entity,String cluster,Date nominalTime){ ConcurrentMap<Date,Date> pendingInstances=pendingJobs.get(getKey(entity,cluster)); if (pendingInstances != null) { LOG.debug("Removing from pending jobs: " + getKey(entity,cluster) + " ---> "+ SchemaHelper.formatDateUTC(nominalTime)); pendingInstances.remove(nominalTime); } }
Example 33
From project jafka, under directory /src/main/java/com/sohu/jafka/producer/.
Source file: ProducerPool.java

public ProducerPool(ProducerConfig config,Encoder<V> serializer,ConcurrentMap<Integer,SyncProducer> syncProducers,ConcurrentMap<Integer,AsyncProducer<V>> asyncProducers,EventHandler<V> inputEventHandler,CallbackHandler<V> callbackHandler){ super(); this.config=config; this.serializer=serializer; this.syncProducers=syncProducers; this.asyncProducers=asyncProducers; this.eventHandler=inputEventHandler != null ? inputEventHandler : new DefaultEventHandler<V>(config,callbackHandler); this.callbackHandler=callbackHandler; if (serializer == null) { throw new InvalidConfigException("serializer passed in is null!"); } this.sync=!"async".equalsIgnoreCase(config.getProducerType()); }
Example 34
From project jboss-marshalling, under directory /api/src/main/java/org/jboss/marshalling/reflect/.
Source file: SerializableClassRegistry.java

/** * Look up serialization information for a class. The resultant object will be cached. * @param subject the class to look up * @return the serializable class information */ public SerializableClass lookup(final Class<?> subject){ if (subject == null) { return null; } final ClassLoader classLoader=subject.getClassLoader(); ConcurrentMap<Class<?>,SerializableClass> loaderMap=registry.get(classLoader); if (loaderMap == null) { final ConcurrentMap<Class<?>,SerializableClass> existing=registry.putIfAbsent(classLoader,loaderMap=new UnlockedHashMap<Class<?>,SerializableClass>()); if (existing != null) { loaderMap=existing; } } SerializableClass info=loaderMap.get(subject); if (info != null) { return info; } final SecurityManager sm=System.getSecurityManager(); if (sm != null) { info=AccessController.doPrivileged(new PrivilegedAction<SerializableClass>(){ public SerializableClass run(){ return new SerializableClass(subject); } } ); } else { info=new SerializableClass(subject); } final SerializableClass existing=loaderMap.putIfAbsent(subject,info); return existing != null ? existing : info; }
Example 35
From project jboss-msc, under directory /src/main/java/org/jboss/msc/service/.
Source file: ServiceContainerImpl.java

/** * Atomically get or create a registration. * @param name the service name * @return the registration */ private ServiceRegistrationImpl getOrCreateRegistration(final ServiceName name){ final ConcurrentMap<ServiceName,ServiceRegistrationImpl> registry=this.registry; ServiceRegistrationImpl registration; registration=registry.get(name); if (registration == null) { registration=new ServiceRegistrationImpl(this,name); ServiceRegistrationImpl existing=registry.putIfAbsent(name,registration); if (existing != null) { return existing; } else { return registration; } } else { return registration; } }
Example 36
From project jboss-remoting, under directory /src/main/java/org/jboss/remoting3/.
Source file: EndpointImpl.java

private MapRegistration(final ConcurrentMap<String,T> map,final String key,final T value){ super(worker,false); this.map=map; this.key=key; this.value=value; }
Example 37
/** * Mount a filesystem on a mount point in the VFS. The mount point is any valid file name, existent or non-existent. If a relative path is given, it will be treated as relative to the VFS root. * @param mountPoint the mount point * @param fileSystem the file system to mount * @return a handle which can be used to unmount the filesystem * @throws IOException if an I/O error occurs, such as a filesystem already being mounted at the given mount point */ public static Closeable mount(VirtualFile mountPoint,FileSystem fileSystem) throws IOException { final VirtualFile parent=mountPoint.getParent(); if (parent == null) { throw new IOException("Root filesystem already mounted"); } final String name=mountPoint.getName(); final Mount mount=new Mount(fileSystem,mountPoint); final ConcurrentMap<VirtualFile,Map<String,Mount>> mounts=VFS.mounts; for (; ; ) { Map<String,Mount> childMountMap=mounts.get(parent); Map<String,Mount> newMap; if (childMountMap == null) { childMountMap=mounts.putIfAbsent(parent,Collections.singletonMap(name,mount)); if (childMountMap == null) { return mount; } } newMap=new HashMap<String,Mount>(childMountMap); if (newMap.put(name,mount) != null) { throw new IOException("Filesystem already mounted at mount point \"" + mountPoint + "\""); } if (mounts.replace(parent,childMountMap,newMap)) { log.tracef("Mounted filesystem %s on mount point %s",fileSystem,mountPoint); return mount; } } }
Example 38
From project JDBM3, under directory /src/main/java/org/apache/jdbm/.
Source file: DBAbstract.java

synchronized public <K,V>ConcurrentMap<K,V> getHashMap(String name){ Object o=getCollectionInstance(name); if (o != null) return (ConcurrentMap<K,V>)o; try { long recid=getNamedObject(name); if (recid == 0) return null; HTree tree=fetch(recid); tree.setPersistenceContext(this); if (!tree.hasValues()) { throw new ClassCastException("HashSet is not HashMap"); } collections.put(name,new WeakReference<Object>(tree)); return tree; } catch ( IOException e) { throw new IOError(e); } }
Example 39
From project Journal.IO, under directory /src/main/java/journal/io/api/.
Source file: DataFileAccessor.java

void dispose(DataFile dataFile){ for ( Entry<Thread,ConcurrentMap<Integer,RandomAccessFile>> threadRafs : perThreadDataFileRafs.entrySet()) { for ( Entry<Integer,RandomAccessFile> raf : threadRafs.getValue().entrySet()) { if (raf.getKey().equals(dataFile.getDataFileId())) { Lock lock=getOrCreateLock(threadRafs.getKey(),raf.getKey()); lock.lock(); try { removeRaf(threadRafs.getKey(),raf.getKey()); return; } catch ( IOException ex) { warn(ex,ex.getMessage()); } finally { lock.unlock(); } } } } }
Example 40
From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/server/handlers/.
Source file: BrowserQueryResponseHandler.java

@Inject public BrowserQueryResponseHandler(HttpServletRequest request,HttpServletResponse response,CapturedBrowsers browsers,ConcurrentMap<SlaveBrowser,List<String>> streamedResponses){ this.request=request; this.response=response; this.browsers=browsers; this.streamedResponses=streamedResponses; }
Example 41
From project karaf, under directory /shell/console/src/main/java/org/apache/karaf/shell/commands/converter/.
Source file: DefaultConverter.java

private static Class getMap(Class type){ if (hasDefaultConstructor(type)) { return type; } else if (SortedMap.class.isAssignableFrom(type)) { return TreeMap.class; } else if (ConcurrentMap.class.isAssignableFrom(type)) { return ConcurrentHashMap.class; } else { return LinkedHashMap.class; } }
Example 42
From project kernel_1, under directory /exo.kernel.component.ext.cache.impl.infinispan.v5/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/.
Source file: DistributedExoCache.java

/** * {@inheritDoc} */ @SuppressWarnings("rawtypes") public void addCacheListener(CacheListener<? super K,? super V> listener){ if (listener == null) { throw new IllegalArgumentException("The listener cannot be null"); } List<ListenerContext> lListeners=getListeners(fullName); if (lListeners == null) { lListeners=new CopyOnWriteArrayList<ListenerContext>(); boolean alreadyAdded=false; ConcurrentMap<String,List<ListenerContext>> listeners=getOrCreateListeners(); if (listeners.isEmpty()) { synchronized (listeners) { if (listeners.isEmpty()) { cache.addListener(new CacheEventListener()); listeners.put(fullName,lListeners); alreadyAdded=true; } } } if (!alreadyAdded) { List<ListenerContext> oldValue=listeners.putIfAbsent(fullName,lListeners); if (oldValue != null) { lListeners=oldValue; } } } lListeners.add(new ListenerContext<K,V>(listener,this)); }
Example 43
From project mcore, under directory /src/com/massivecraft/mcore4/xlib/bson/util/.
Source file: ClassAncestry.java

/** * getAncestry Walks superclass and interface graph, superclasses first, then interfaces, to compute an ancestry list. Supertypes are visited left to right. Duplicates are removed such that no Class will appear in the list before one of its subtypes. Does not need to be synchronized, races are harmless as the Class graph does not change at runtime. */ public static <T>List<Class<?>> getAncestry(Class<T> c){ final ConcurrentMap<Class<?>,List<Class<?>>> cache=getClassAncestryCache(); while (true) { List<Class<?>> cachedResult=cache.get(c); if (cachedResult != null) { return cachedResult; } cache.putIfAbsent(c,computeAncestry(c)); } }
Example 44
From project meteo, under directory /core/src/main/java/com/ning/metrics/meteo/server/resources/.
Source file: StreamResource.java

private Response buildJsonpResponse(final String attribute,final Cache<Object,Object> samples,final String callback){ try { final ByteArrayOutputStream out=new ByteArrayOutputStream(); final JsonGenerator generator=objectMapper.getJsonFactory().createJsonGenerator(out); generator.writeStartObject(); generator.writeFieldName("attribute"); generator.writeString(attribute); generator.writeFieldName("samples"); generator.writeStartArray(); if (samples != null) { final ConcurrentMap<Object,Object> samplesForType=samples.asMap(); final List<DateTime> timestamps=new ArrayList<DateTime>(); for ( final Object timestamp : samplesForType.keySet()) { timestamps.add((DateTime)timestamp); } Collections.sort(timestamps); for ( final DateTime timestamp : timestamps) { final Object dataPoint=samplesForType.get(timestamp); if (dataPoint != null) { generator.writeNumber(unixSeconds(timestamp)); generator.writeObject(dataPoint); } } } generator.writeEndArray(); generator.writeEndObject(); generator.close(); final JSONPObject object=new JSONPObject(callback,out.toString()); return Response.ok(object).build(); } catch ( IOException e) { log.error("Error",e); return Response.serverError().build(); } }
Example 45
From project mongo-java-driver, under directory /src/main/org/bson/util/.
Source file: ClassAncestry.java

/** * getAncestry Walks superclass and interface graph, superclasses first, then interfaces, to compute an ancestry list. Supertypes are visited left to right. Duplicates are removed such that no Class will appear in the list before one of its subtypes. Does not need to be synchronized, races are harmless as the Class graph does not change at runtime. */ public static <T>List<Class<?>> getAncestry(Class<T> c){ final ConcurrentMap<Class<?>,List<Class<?>>> cache=getClassAncestryCache(); while (true) { List<Class<?>> cachedResult=cache.get(c); if (cachedResult != null) { return cachedResult; } cache.putIfAbsent(c,computeAncestry(c)); } }
Example 46
From project netty, under directory /common/src/main/java/io/netty/util/.
Source file: UniqueName.java

/** * Constructs a new {@link UniqueName} * @param map the map of names to compare with * @param name the name of this {@link UniqueName} * @param args the arguments to process */ public UniqueName(ConcurrentMap<String,Boolean> map,String name,Object... args){ if (map == null) { throw new NullPointerException("map"); } if (name == null) { throw new NullPointerException("name"); } if (args != null && args.length > 0) { validateArgs(args); } if (map.putIfAbsent(name,Boolean.TRUE) != null) { throw new IllegalArgumentException(String.format("'%s' is already in use",name)); } id=nextId.incrementAndGet(); this.name=name; }
Example 47
From project openwebbeans, under directory /webbeans-impl/src/main/java/org/apache/webbeans/context/.
Source file: AbstractContext.java

@SuppressWarnings("unchecked") private <T>void createContextualBag(Contextual<T> contextual,CreationalContext<T> creationalContext){ BeanInstanceBag<T> bag=new BeanInstanceBag<T>(creationalContext); if (componentInstanceMap instanceof ConcurrentMap) { T exist=(T)((ConcurrentMap)componentInstanceMap).putIfAbsent(contextual,bag); if (exist == null) { componentInstanceMap.put(contextual,bag); } } else { componentInstanceMap.put(contextual,bag); } }
Example 48
From project org.ops4j.pax.swissbox, under directory /pax-swissbox-converter/src/main/java/org/ops4j/pax/swissbox/converter/java/util/.
Source file: ToMapConverter.java

private static Class<? extends Map> getMapType(final Class type){ if (Reflection.hasDefaultConstructor(type)) { return type; } else if (SortedMap.class.isAssignableFrom(type)) { return TreeMap.class; } else if (ConcurrentMap.class.isAssignableFrom(type)) { return ConcurrentHashMap.class; } else { return LinkedHashMap.class; } }
Example 49
From project pepe, under directory /pepe/src/edu/stanford/pepe/newpostprocessing/.
Source file: BytecodeInstrumentationInterpreter.java

public void load(String file) throws IOException, ClassNotFoundException { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file)); try { @SuppressWarnings("unchecked") ConcurrentMap<StackTrace,List<IncompleteExecution>> executions=(ConcurrentMap<StackTrace,List<IncompleteExecution>>)ois.readObject(); processExecutions(executions); } finally { ois.close(); } }
Example 50
From project platform_3, under directory /configuration/src/main/java/com/proofpoint/configuration/testing/.
Source file: ConfigAssertions.java

public static <T>T recordDefaults(Class<T> type){ final T instance=newDefaultInstance(type); T proxy=(T)Enhancer.create(type,new Class[]{$$RecordingConfigProxy.class},new MethodInterceptor(){ private final ConcurrentMap<Method,Object> invokedMethods=new MapMaker().makeMap(); @Override public Object intercept( Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if (GET_RECORDING_CONFIG_METHOD.equals(method)) { return new $$RecordedConfigData<T>(instance,ImmutableSet.copyOf(invokedMethods.keySet())); } invokedMethods.put(method,Boolean.TRUE); Object result=methodProxy.invoke(instance,args); if (result == instance) { return proxy; } else { return result; } } } ); return proxy; }
Example 51
From project platform_external_guava, under directory /src/com/google/common/collect/.
Source file: CustomConcurrentHashMap.java

/** * Creates a new concurrent hash map backed by the given strategy. * @param strategy used to implement and manipulate the entries * @param < K > the type of keys to be stored in the returned map * @param < V > the type of values to be stored in the returned map * @param < E > the type of internal entry to be stored in the returned map * @throws NullPointerException if strategy is null */ public <K,V,E>ConcurrentMap<K,V> buildMap(Strategy<K,V,E> strategy){ if (strategy == null) { throw new NullPointerException("strategy"); } return new Impl<K,V,E>(strategy,this); }
Example 52
From project sitebricks, under directory /sitebricks/src/test/java/com/google/sitebricks/rendering/.
Source file: DynTypedMvelEvaluatorCompiler.java

public Evaluator compile(final String expression) throws ExpressionCompileException { return new Evaluator(){ private final ConcurrentMap<String,Serializable> map=new ConcurrentHashMap<String,Serializable>(); @Nullable public Object evaluate( String ___expr, Object bean){ Serializable serializable=map.get(expression); if (null == serializable) { serializable=MVEL.compileExpression(expression); map.put(expression,serializable); } return MVEL.executeExpression(serializable,bean); } public void write( String expr, Object bean, Object value){ } public Object read( String property, Object contextObject){ return MVEL.getProperty(property,contextObject); } } ; }
Example 53
public AnalyzeTree(RootedTree currentTree,String precisionString,String coordinatesName,String rateString,double[] sliceHeights,double timescaler,ThreadLocalSpreadDate mrsd,ConcurrentMap<Double,List<Coordinates>> slicesMap,boolean useTrueNoise){ this.currentTree=currentTree; this.precisionString=precisionString; this.coordinatesName=coordinatesName; this.rateString=rateString; this.sliceHeights=sliceHeights; this.timescaler=timescaler; this.mrsd=mrsd; this.slicesMap=slicesMap; this.useTrueNoise=useTrueNoise; }
Example 54
From project spring-gemfire, under directory /src/main/java/org/springframework/data/gemfire/.
Source file: PartitionedRegionFactoryBean.java

@Override protected void resolveDataPolicy(RegionFactory<K,V> regionFactory,Boolean persistent,String dataPolicy){ if (dataPolicy != null) { DataPolicy dp=new DataPolicyConverter().convert(dataPolicy); Assert.notNull(dp,"Data policy " + dataPolicy + " is invalid"); Assert.isTrue(dp.withPartitioning(),"Data Policy " + dp.toString() + " is not supported in partitioned regions"); if (!isPersistent()) { regionFactory.setDataPolicy(dp); } else { Assert.isTrue(dp.withPersistence(),"Data Policy " + dp.toString() + "is invalid when persistent is false"); regionFactory.setDataPolicy(dp); } return; } if (isPersistent()) { if (ConcurrentMap.class.isAssignableFrom(Region.class)) { regionFactory.setDataPolicy(DataPolicy.PERSISTENT_PARTITION); } else { throw new IllegalArgumentException("Can define persistent partitions only from GemFire 6.5 onwards - current version is [" + CacheFactory.getVersion() + "]"); } } else { regionFactory.setDataPolicy(DataPolicy.PARTITION); } }
Example 55
From project tb-diamond_1, under directory /diamond-client/src/main/java/com/taobao/diamond/client/impl/.
Source file: DefaultSubscriberListener.java

public List<ManagerListener> getManagerListenerList(String dataId,String group,String instanceId){ if (null == dataId || null == instanceId) { return null; } List<ManagerListener> ret=null; String key=makeKey(dataId,group); ConcurrentMap<String,CopyOnWriteArrayList<ManagerListener>> map=allListeners.get(key); if (map != null) { ret=map.get(instanceId); if (ret != null) { ret=new ArrayList<ManagerListener>(ret); } } return ret; }
Example 56
From project TomP2P, under directory /src/main/java/net/tomp2p/storage/.
Source file: TrackerStorage.java

private boolean storeData(PeerAddress peerAddress,byte[] attachement,int offset,int length,Number160 peerId,Number320 key,ConcurrentMap<Number320,Map<Number160,TrackerData>> trackerData,ConcurrentMap<Number160,Collection<Number320>> reverseTrackerData,int factor){ Map<Number160,TrackerData> data=new ConcurrentCacheMap<Number160,TrackerData>(trackerTimoutSeconds,1000,true); Map<Number160,TrackerData> data2=trackerData.putIfAbsent(key,data); data=data2 == null ? data : data2; if (data.size() > TRACKER_SIZE * factor) return false; data.put(peerId,new TrackerData(peerAddress,null,attachement,offset,length)); Collection<Number320> collection=new HashSet<Number320>(); Collection<Number320> collection2=reverseTrackerData.putIfAbsent(peerId,collection); collection=collection2 == null ? collection : collection2; synchronized (collection) { collection.add(key); } return true; }
Example 57
From project tools4j, under directory /config/config-core/src/main/java/org/deephacks/tools4j/config/internal/core/runtime/.
Source file: BeanToObjectConverter.java

@SuppressWarnings("unchecked") private static Map<Object,Object> newMap(Class<?> clazz){ if (!clazz.isInterface()) { try { return (Map<Object,Object>)clazz.newInstance(); } catch ( Exception e) { throw new RuntimeException(e); } } if (Map.class.isAssignableFrom(clazz)) { return new HashMap<Object,Object>(); } else if (ConcurrentMap.class.isAssignableFrom(clazz)) { return new ConcurrentHashMap<Object,Object>(); } throw new UnsupportedOperationException("Class [" + clazz + "] is not supported."); }
Example 58
From project vert.x, under directory /vertx-core/src/main/java/org/vertx/java/core/shareddata/.
Source file: SharedData.java

/** * Return a {@code Map} with the specific {@code name}. All invocations of this method with the same value of {@code name}are guaranteed to return the same {@code Map} instance. <p> */ public <K,V>ConcurrentMap<K,V> getMap(String name){ SharedMap<K,V> map=(SharedMap<K,V>)maps.get(name); if (map == null) { map=new SharedMap<>(); SharedMap prev=maps.putIfAbsent(name,map); if (prev != null) { map=prev; } } return map; }
Example 59
From project whirr, under directory /core/src/main/java/org/apache/whirr/service/.
Source file: DryRunModule.java

@SuppressWarnings("unused") @Inject public Factory(final ConcurrentMap<String,NodeMetadata> nodes){ this.clientMap=CacheBuilder.newBuilder().build(new CacheLoader<Key,SshClient>(){ @Override public SshClient load( Key key){ return new LogSshClient(key); } } ); this.nodes=nodes; }
Example 60
From project zanata, under directory /zanata-war/src/test/java/org/zanata/webtrans/server/.
Source file: TranslationWorkspaceImplTest.java

@Test public void onTimeoutRemove(){ ConcurrentMap<EditorClientId,PersonId> sessions=new MapMaker().makeMap(); sessions.put(new EditorClientId("a",1),new PersonId("person a")); sessions.put(new EditorClientId("b",1),new PersonId("person b")); sessions.remove(new EditorClientId("a",1)); }