Java Code Examples for java.util.concurrent.ConcurrentMap#put()
The following examples show how to use
java.util.concurrent.ConcurrentMap#put() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractBfnRule.java From light with Apache License 2.0 | 6 votes |
protected List<String> getRecentEntityList(String host, String categoryType, String sortedBy, String sortDir) { List<String> list = null; // get list from cache Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap"); ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>)categoryMap.get("listCache"); if(listCache == null) { listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>() .maximumWeightedCapacity(200) .build(); categoryMap.put("listCache", listCache); } else { list = (List<String>)listCache.get(host + categoryType); } if(list == null) { // not in cache, get from db list = getRecentEntityListDb(host, categoryType, sortedBy, sortDir); if(list != null) { listCache.put(host + categoryType, list); } } return list; }
Example 2
Source File: ASMUtils.java From joyqueue with Apache License 2.0 | 6 votes |
/** * 获得方法参数名称和类型, 基本类型会转换为包装类型 * 没处理重载方法 * * @param type * @param methodName * @return */ public static Map<String /** name **/, Class<?> /** type**/> getParams(Class<?> type, String methodName) { ConcurrentMap<String, Map<String, Class<?>>> methodParamsCache = paramsCache.get(type); if (methodParamsCache == null) { methodParamsCache = new ConcurrentHashMap<>(); ConcurrentMap<String, Map<String, Class<?>>> oldMethodParamsCache = paramsCache.putIfAbsent(type, methodParamsCache); if (oldMethodParamsCache != null) { methodParamsCache = oldMethodParamsCache; } } Map<String, Class<?>> result = methodParamsCache.get(methodName); if (result != null) { return result; } result = doGetParams(type, methodName); methodParamsCache.put(methodName, result); return result; }
Example 3
Source File: DefaultMessageStore.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 5 votes |
private void putConsumeQueue(final String topic, final int queueId, final ConsumeQueue consumeQueue) { ConcurrentMap<Integer/* queueId */, ConsumeQueue> map = this.consumeQueueTable.get(topic); if (null == map) { map = new ConcurrentHashMap<Integer/* queueId */, ConsumeQueue>(); map.put(queueId, consumeQueue); this.consumeQueueTable.put(topic, map); } else { map.put(queueId, consumeQueue); } }
Example 4
Source File: SimpleVirtualFlowObjectiveStore.java From onos with Apache License 2.0 | 5 votes |
@Override public void putNextGroup(NetworkId networkId, Integer nextId, NextGroup group) { ConcurrentMap<Integer, byte[]> nextGroups = getNextGroups(networkId); nextGroups.put(nextId, group.data()); updateNextGroupsMap(networkId, nextGroups); eventQ.add(new VirtualObjectiveEvent(networkId, ObjectiveEvent.Type.ADD, nextId)); }
Example 5
Source File: BlobStoreModule.java From emodb with Apache License 2.0 | 5 votes |
@Provides @Singleton @MinLagDurationValues Map<String, ValueStore<Duration>> provideMinLagDurationValues(@CassandraClusters Collection<String> cassandraClusters, @GlobalFullConsistencyZooKeeper final CuratorFramework curator, final LifeCycleRegistry lifeCycle) { final ConcurrentMap<String, ValueStore<Duration>> valuesByCluster = Maps.newConcurrentMap(); for (String cluster : cassandraClusters) { String zkPath = ZKPaths.makePath("/consistency/min-lag", cluster); ZkValueStore<Duration> holder = new ZkValueStore<>(curator, zkPath, new ZkDurationSerializer()); valuesByCluster.put(cluster, lifeCycle.manage(holder)); } return valuesByCluster; }
Example 6
Source File: Issue30Test.java From caffeine with Apache License 2.0 | 5 votes |
private void initialValues(AsyncLoadingCache<String, String> cache, ConcurrentMap<String, String> source, ConcurrentMap<String, Instant> lastLoad) throws InterruptedException, ExecutionException { source.put(A_KEY, A_ORIGINAL); source.put(B_KEY, B_ORIGINAL); lastLoad.clear(); assertThat("should serve initial value", cache.get(A_KEY), is(futureOf(A_ORIGINAL))); assertThat("should serve initial value", cache.get(B_KEY), is(futureOf(B_ORIGINAL))); }
Example 7
Source File: AlphaPb.java From ET_Redux with Apache License 2.0 | 5 votes |
/** * * @param inputValueModels * @param parDerivTerms */ @Override public void calculateValue( ValueModel[] inputValueModels, ConcurrentMap<String, BigDecimal> parDerivTerms) { r202_205m = inputValueModels[0]; r202_205t = inputValueModels[1]; // perform analysis to determine which of the four techniques applies if (fractionMeanAlphaPb.compareTo(BigDecimal.ZERO) == 0) { if (r202_205m.getValue().compareTo(BigDecimal.ZERO) == 1) { // case 2 CalculateValueI(parDerivTerms); } else { // case 3 // moved back to reducer to support Kwiki sensitivity use copyValuesFrom(alphaPbModel); } } else { // case 1 value stays at 0 // sept 19 2010 email Form Noah re: special case value = BigDecimal.ZERO; setValueTree(ExpTreeII.ZERO); // alphaPb needs to be restored after reduction setOneSigma(BigDecimal.ZERO); try { BigDecimal dAlphaPb__dR202_205t =BigDecimal.ONE.negate().// divide(new BigDecimal("3.0", ReduxConstants.mathContext15).// multiply(r202_205m.getValue()), ReduxConstants.mathContext15); parDerivTerms.put("dAlphaPb__dR202_205t", dAlphaPb__dR202_205t); } catch (Exception e) { parDerivTerms.put("dAlphaPb__dR202_205t", BigDecimal.ZERO); } } }
Example 8
Source File: DistributedGroupStore.java From onos with Apache License 2.0 | 5 votes |
@Override public void addOrUpdateExtraneousGroupEntry(Group group) { log.debug("add/update extraneous group entry {} in device {}", group.id(), group.deviceId()); ConcurrentMap<GroupId, Group> extraneousIdTable = getExtraneousGroupIdTable(group.deviceId()); extraneousIdTable.put(group.id(), group); // Don't remove the extraneous groups, instead re-use it when // a group request comes with the same set of buckets }
Example 9
Source File: AgentBuilderTypeLocatorWithTypePoolCacheSimpleTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test public void testSimpleImplementation() throws Exception { ConcurrentMap<ClassLoader, TypePool.CacheProvider> cacheProviders = new ConcurrentHashMap<ClassLoader, TypePool.CacheProvider>(); cacheProviders.put(first, firstCache); cacheProviders.put(second, secondCache); AgentBuilder.PoolStrategy poolStrategy = new AgentBuilder.PoolStrategy.WithTypePoolCache.Simple(TypePool.Default.ReaderMode.FAST, cacheProviders); assertThat(poolStrategy.typePool(classFileLocator, first), hasPrototype(poolStrategy.typePool(classFileLocator, first))); assertThat(poolStrategy.typePool(classFileLocator, first), not(hasPrototype(poolStrategy.typePool(classFileLocator, second)))); }
Example 10
Source File: BTreeMapLargeValsTest.java From scava with Eclipse Public License 2.0 | 5 votes |
@Override protected ConcurrentMap<Integer, String> makePopulatedMap() throws UnsupportedOperationException { ConcurrentMap<Integer, String> map = makeEmptyMap(); for (int i = 0; i < 100; i++){ map.put(i, aa+"aa" + i); } return map; }
Example 11
Source File: RemoteCacheTests.java From bazel with Apache License 2.0 | 5 votes |
@Test public void testDownloadDirectory() throws Exception { // Test that downloading an output directory works. // arrange final ConcurrentMap<Digest, byte[]> cas = new ConcurrentHashMap<>(); Digest fooDigest = digestUtil.computeAsUtf8("foo-contents"); cas.put(fooDigest, "foo-contents".getBytes(Charsets.UTF_8)); Digest quxDigest = digestUtil.computeAsUtf8("qux-contents"); cas.put(quxDigest, "qux-contents".getBytes(Charsets.UTF_8)); Tree barTreeMessage = Tree.newBuilder() .setRoot( Directory.newBuilder() .addFiles( FileNode.newBuilder() .setName("qux") .setDigest(quxDigest) .setIsExecutable(true))) .build(); Digest barTreeDigest = digestUtil.compute(barTreeMessage); cas.put(barTreeDigest, barTreeMessage.toByteArray()); ActionResult.Builder result = ActionResult.newBuilder(); result.addOutputFilesBuilder().setPath("a/foo").setDigest(fooDigest); result.addOutputDirectoriesBuilder().setPath("a/bar").setTreeDigest(barTreeDigest); // act RemoteCache remoteCache = newRemoteCache(cas); remoteCache.download(result.build(), execRoot, null, /* outputFilesLocker= */ () -> {}); // assert assertThat(digestUtil.compute(execRoot.getRelative("a/foo"))).isEqualTo(fooDigest); assertThat(digestUtil.compute(execRoot.getRelative("a/bar/qux"))).isEqualTo(quxDigest); assertThat(execRoot.getRelative("a/bar/qux").isExecutable()).isTrue(); }
Example 12
Source File: FileBasedRegistrationService.java From hono with Eclipse Public License 2.0 | 5 votes |
private OperationResult<Id> doUpdateDevice(final String tenantId, final String deviceId, final Device device, final Optional<String> resourceVersion, final Span span) { final ConcurrentMap<String, Versioned<Device>> devices = identities.get(tenantId); if (devices == null) { TracingHelper.logError(span, "No devices found for tenant"); return Result.from(HttpURLConnection.HTTP_NOT_FOUND, OperationResult::empty); } final Versioned<Device> currentDevice = devices.get(deviceId); if (currentDevice == null) { TracingHelper.logError(span, "Device not found"); return Result.from(HttpURLConnection.HTTP_NOT_FOUND, OperationResult::empty); } final Versioned<Device> newDevice = currentDevice.update(resourceVersion, () -> device); if (newDevice == null) { TracingHelper.logError(span, "Resource Version mismatch"); return Result.from(HttpURLConnection.HTTP_PRECON_FAILED, OperationResult::empty); } devices.put(deviceId, newDevice); dirty.set(true); return OperationResult.ok(HttpURLConnection.HTTP_NO_CONTENT, Id.of(deviceId), Optional.empty(), Optional.ofNullable(newDevice.getVersion())); }
Example 13
Source File: ConcurrentHashMapTest.java From caffeine with Apache License 2.0 | 5 votes |
/** * remove(null) throws NPE */ public void testRemove1_NullPointerException() { ConcurrentMap c = map(); c.put("sadsdf", "asdads"); try { c.remove(null); shouldThrow(); } catch (NullPointerException success) {} }
Example 14
Source File: MapUtilTest.java From vjtools with Apache License 2.0 | 4 votes |
private void initExpireKeyMap(ConcurrentMap<MyBean, MyBean> weakKeyMap, MyBean value) { MyBean key = new MyBean("A"); weakKeyMap.put(key, value); assertThat(weakKeyMap.get(key)).isEqualTo(value); }
Example 15
Source File: Glob.java From idea-gitignore with MIT License | 4 votes |
/** * Finds for {@link VirtualFile} list using glob rule in given root directory. * * @param root root directory * @param entries ignore entries * @param includeNested attach children to the search result * @return search result */ @NotNull public static Map<IgnoreEntry, List<VirtualFile>> find(@NotNull final VirtualFile root, @NotNull List<IgnoreEntry> entries, @NotNull final MatcherUtil matcher, final boolean includeNested) { final ConcurrentMap<IgnoreEntry, List<VirtualFile>> result = ContainerUtil.newConcurrentMap(); final HashMap<IgnoreEntry, Pattern> map = new HashMap<>(); for (IgnoreEntry entry : entries) { result.put(entry, new ArrayList<>()); final Pattern pattern = createPattern(entry); if (pattern != null) { map.put(entry, pattern); } } VirtualFileVisitor<HashMap<IgnoreEntry, Pattern>> visitor = new VirtualFileVisitor<HashMap<IgnoreEntry, Pattern>>(VirtualFileVisitor.NO_FOLLOW_SYMLINKS) { @Override public boolean visitFile(@NotNull VirtualFile file) { if (root.equals(file)) { return true; } final HashMap<IgnoreEntry, Pattern> current = new HashMap<>(); if (getCurrentValue().isEmpty()) { return false; } final String path = Utils.getRelativePath(root, file); if (path == null || Utils.isVcsDirectory(file)) { return false; } for (Map.Entry<IgnoreEntry, Pattern> item : getCurrentValue().entrySet()) { final Pattern value = item.getValue(); boolean matches = false; if (value == null || matcher.match(value, path)) { matches = true; result.get(item.getKey()).add(file); } if (includeNested && matches) { current.put(item.getKey(), null); } else { current.put(item.getKey(), item.getValue()); } } setValueForChildren(current); return true; } }; visitor.setValueForChildren(map); VfsUtil.visitChildrenRecursively(root, visitor); return result; }
Example 16
Source File: SimpleGroupStore.java From onos with Apache License 2.0 | 4 votes |
/** * Updates the existing group entry with the information * from group description. * * @param deviceId the device ID * @param oldAppCookie the current group key * @param type update type * @param newBuckets group buckets for updates * @param newAppCookie optional new group key */ @Override public void updateGroupDescription(DeviceId deviceId, GroupKey oldAppCookie, UpdateType type, GroupBuckets newBuckets, GroupKey newAppCookie) { // Check if a group is existing with the provided key Group oldGroup = getGroup(deviceId, oldAppCookie); if (oldGroup == null) { return; } List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup, type, newBuckets); if (newBucketList != null) { // Create a new group object from the old group GroupBuckets updatedBuckets = new GroupBuckets(newBucketList); GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie; GroupDescription updatedGroupDesc = new DefaultGroupDescription( oldGroup.deviceId(), oldGroup.type(), updatedBuckets, newCookie, oldGroup.givenGroupId(), oldGroup.appId()); StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(), updatedGroupDesc); newGroup.setState(GroupState.PENDING_UPDATE); newGroup.setLife(oldGroup.life()); newGroup.setPackets(oldGroup.packets()); newGroup.setBytes(oldGroup.bytes()); // Remove the old entry from maps and add new entry using new key ConcurrentMap<GroupKey, StoredGroupEntry> keyTable = getGroupKeyTable(oldGroup.deviceId()); ConcurrentMap<GroupId, StoredGroupEntry> idTable = getGroupIdTable(oldGroup.deviceId()); keyTable.remove(oldGroup.appCookie()); idTable.remove(oldGroup.id()); keyTable.put(newGroup.appCookie(), newGroup); idTable.put(newGroup.id(), newGroup); notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup)); } }
Example 17
Source File: ConsumeQueueManager.java From DeFiBus with Apache License 2.0 | 4 votes |
public void recordLastDeliverOffset(final String group, final String topic, final int queueId, final long offset) { String key = topic + TOPIC_GROUP_SEPARATOR + group; this.lastDeliverOffsetTable.putIfAbsent(key, new ConcurrentHashMap<Integer, Long>(32)); ConcurrentMap<Integer, Long> map = this.lastDeliverOffsetTable.get(key); map.put(queueId, offset); }
Example 18
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 4 votes |
public void disabled_testInvalidateDuringLoading() throws InterruptedException { // computation starts; invalidate() is called on the key being computed, computation finishes final CountDownLatch computationStarted = new CountDownLatch(2); final CountDownLatch letGetFinishSignal = new CountDownLatch(1); final CountDownLatch getFinishedSignal = new CountDownLatch(2); final String getKey = "get"; final String refreshKey = "refresh"; final String suffix = "Suffix"; CacheLoader<String, String> computeFunction = new CacheLoader<String, String>() { @Override public String load(String key) { computationStarted.countDown(); assertTrue(Uninterruptibles.awaitUninterruptibly( letGetFinishSignal, 300, TimeUnit.SECONDS)); return key + suffix; } }; final LoadingCache<String, String> cache = CaffeinatedGuava.build( Caffeine.newBuilder(), computeFunction); ConcurrentMap<String,String> map = cache.asMap(); map.put(refreshKey, refreshKey); new Thread(() -> { cache.getUnchecked(getKey); getFinishedSignal.countDown(); }).start(); new Thread(() -> { cache.refresh(refreshKey); getFinishedSignal.countDown(); }).start(); assertTrue(computationStarted.await(300, TimeUnit.SECONDS)); cache.invalidate(getKey); cache.invalidate(refreshKey); assertFalse(map.containsKey(getKey)); assertFalse(map.containsKey(refreshKey)); // let computation complete letGetFinishSignal.countDown(); assertTrue(getFinishedSignal.await(300, TimeUnit.SECONDS)); checkNothingLogged(); // results should be visible assertEquals(2, cache.size()); assertEquals(getKey + suffix, map.get(getKey)); assertEquals(refreshKey + suffix, map.get(refreshKey)); assertEquals(2, cache.size()); }
Example 19
Source File: StandardQueueEntryListTest.java From qpid-broker-j with Apache License 2.0 | 4 votes |
@Test public void testScavenge() throws Exception { StandardQueueImpl mockQueue = mock(StandardQueueImpl.class); when(mockQueue.getContextValue(Integer.class, QUEUE_SCAVANGE_COUNT)).thenReturn(9); OrderedQueueEntryList sqel = new StandardQueueEntryList(mockQueue, new QueueStatistics()); ConcurrentMap<Integer,QueueEntry> entriesMap = new ConcurrentHashMap<Integer,QueueEntry>(); //Add messages to generate QueueEntry's for(int i = 1; i <= 100 ; i++) { QueueEntry bleh = sqel.add(createServerMessage(i), null); assertNotNull("QE should not have been null", bleh); entriesMap.put(i,bleh); } OrderedQueueEntry head = (OrderedQueueEntry) sqel.getHead(); //We shall now delete some specific messages mid-queue that will lead to //requiring a scavenge once the requested threshold of 9 deletes is passed //Delete the 2nd message only assertTrue("Failed to delete QueueEntry", remove(entriesMap, 2)); verifyDeletedButPresentBeforeScavenge(head, 2); //Delete messages 12 to 14 assertTrue("Failed to delete QueueEntry", remove(entriesMap, 12)); verifyDeletedButPresentBeforeScavenge(head, 12); assertTrue("Failed to delete QueueEntry", remove(entriesMap, 13)); verifyDeletedButPresentBeforeScavenge(head, 13); assertTrue("Failed to delete QueueEntry", remove(entriesMap, 14)); verifyDeletedButPresentBeforeScavenge(head, 14); //Delete message 20 only assertTrue("Failed to delete QueueEntry", remove(entriesMap, 20)); verifyDeletedButPresentBeforeScavenge(head, 20); //Delete messages 81 to 84 assertTrue("Failed to delete QueueEntry", remove(entriesMap, 81)); verifyDeletedButPresentBeforeScavenge(head, 81); assertTrue("Failed to delete QueueEntry", remove(entriesMap, 82)); verifyDeletedButPresentBeforeScavenge(head, 82); assertTrue("Failed to delete QueueEntry", remove(entriesMap, 83)); verifyDeletedButPresentBeforeScavenge(head, 83); assertTrue("Failed to delete QueueEntry", remove(entriesMap, 84)); verifyDeletedButPresentBeforeScavenge(head, 84); //Delete message 99 - this is the 10th message deleted that is after the queue head //and so will invoke the scavenge() which is set to go after 9 previous deletions assertTrue("Failed to delete QueueEntry", remove(entriesMap, 99)); verifyAllDeletedMessagedNotPresent(head, entriesMap); }
Example 20
Source File: Age207_235r_Pa.java From ET_Redux with Apache License 2.0 | 4 votes |
/** * * @param inputValueModels * @param parDerivTerms */ @Override public void calculateValue ( ValueModel[] inputValueModels, ConcurrentMap<String, BigDecimal> parDerivTerms ) { ar231_235sample = inputValueModels[0]; r207_235r = inputValueModels[1]; lambda235 = inputValueModels[2]; lambda231 = inputValueModels[3]; // nov 2009 to clean up outputs if ( r207_235r.getValue().compareTo( BigDecimal.ZERO ) == 0 ) { setValue( BigDecimal.ZERO ); setValueTree( ExpTreeII.ZERO ); } else { try { // jan 2011 double value = (1.0 // / lambda235.getValue().doubleValue()) // * (Math.log1p( // r207_235r.getValue().doubleValue() // - (lambda235.getValue().doubleValue() // / lambda231.getValue().doubleValue() )// * (ar231_235sample.getValue().doubleValue() - 1.0) )); setValue(new BigDecimal( value, ReduxConstants.mathContext15 ) ); setValueTree(// ExpTreeII.ONE.// divide( lambda235.getValueTree()).// multiply( r207_235r.getValueTree().// subtract(lambda235.getValueTree().divide( lambda231.getValueTree()).// multiply( ar231_235sample.getValueTree().subtract( ExpTreeII.ONE ))).// add( ExpTreeII.ONE ).log())); } catch (Exception e) { setValue( BigDecimal.ZERO ); setValueTree( ExpTreeII.ZERO ); } // System.out.println(differenceValueCalcs()); // Jan 2011 BigDecimal denominator = // lambda231.getValue().// multiply( BigDecimal.ONE.add( r207_235r.getValue() ) ).// add( lambda235.getValue().// multiply( BigDecimal.ONE.// subtract( ar231_235sample.getValue() ) ) ); // partial derivatives BigDecimal dAge207_235r_Pa__dLambda235 = BigDecimal.ZERO; BigDecimal dAge207_235r_Pa__dR207_235r = BigDecimal.ZERO; BigDecimal dAge207_235r_Pa__dLambda231 = BigDecimal.ZERO; BigDecimal dAge207_235r_Pa__dAr231_235sample = BigDecimal.ZERO; if ( denominator.compareTo( BigDecimal.ZERO ) != 0 ) { dAge207_235r_Pa__dLambda235 = BigDecimal.ONE.// divide(lambda235.getValue(), ReduxConstants.mathContext15).// multiply(BigDecimal.ONE.subtract( ar231_235sample.getValue()).// divide(denominator , ReduxConstants.mathContext15).// subtract( getValue())); dAge207_235r_Pa__dR207_235r = lambda231.getValue().// divide(lambda235.getValue(), ReduxConstants.mathContext15).// divide(denominator, ReduxConstants.mathContext15); dAge207_235r_Pa__dLambda231 = ar231_235sample.getValue().// subtract( BigDecimal.ONE).// divide(lambda231.getValue(), ReduxConstants.mathContext15).// divide(denominator, ReduxConstants.mathContext15); dAge207_235r_Pa__dAr231_235sample = BigDecimal.ONE.negate().// divide(denominator, ReduxConstants.mathContext15); } parDerivTerms.put( "dAge207_235r_Pa__dLambda235", dAge207_235r_Pa__dLambda235 ); parDerivTerms.put( "dAge207_235r_Pa__dR207_235r", dAge207_235r_Pa__dR207_235r ); parDerivTerms.put( "dAge207_235r_Pa__dLambda231", dAge207_235r_Pa__dLambda231 ); parDerivTerms.put( "dAge207_235r_Pa__dAr231_235sample", dAge207_235r_Pa__dAr231_235sample ); } }