com.google.common.collect.Multimaps Java Examples
The following examples show how to use
com.google.common.collect.Multimaps.
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: EventDeadLettersContract.java From james-project with Apache License 2.0 | 6 votes |
@Test default void storeShouldKeepConsistencyWhenConcurrentStore() throws Exception { EventDeadLetters eventDeadLetters = eventDeadLetters(); ImmutableMap<Integer, Group> groups = concurrentGroups(); Multimap<Integer, EventDeadLetters.InsertionId> storedInsertionIds = Multimaps.synchronizedSetMultimap(HashMultimap.create()); ConcurrentTestRunner.builder() .operation((threadNumber, step) -> { Event.EventId eventId = Event.EventId.random(); EventDeadLetters.InsertionId insertionId = eventDeadLetters.store(groups.get(threadNumber), event(eventId)).block(); storedInsertionIds.put(threadNumber, insertionId); }) .threadCount(THREAD_COUNT) .operationCount(OPERATION_COUNT) .runSuccessfullyWithin(RUN_SUCCESSFULLY_IN); groups.forEach((groupId, group) -> { Group storedGroup = groups.get(groupId); assertThat(eventDeadLetters.failedIds(storedGroup).collectList().block()) .hasSameElementsAs(storedInsertionIds.get(groupId)); }); }
Example #2
Source File: ClientAuthInterceptorTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void testCopyCredentialToHeaders() throws IOException { ListMultimap<String, String> values = LinkedListMultimap.create(); values.put("Authorization", "token1"); values.put("Authorization", "token2"); values.put("Extra-Authorization", "token3"); values.put("Extra-Authorization", "token4"); when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values)); ClientCall<String, Integer> interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel); Metadata headers = new Metadata(); interceptedCall.start(listener, headers); assertEquals(listener, call.responseListener); assertEquals(headers, call.headers); Iterable<String> authorization = headers.getAll(AUTHORIZATION); Assert.assertArrayEquals(new String[]{"token1", "token2"}, Iterables.toArray(authorization, String.class)); Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION); Assert.assertArrayEquals(new String[]{"token3", "token4"}, Iterables.toArray(extraAuthorization, String.class)); }
Example #3
Source File: DashboardMain.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
/** * Partitions {@code symbolProblems} by the JAR file that contains the {@link ClassFile}. * * <p>For example, {@code classes = result.get(JarX).get(SymbolProblemY)} where {@code classes} * are not null means that {@code JarX} has {@code SymbolProblemY} and that {@code JarX} contains * {@code classes} which reference {@code SymbolProblemY.getSymbol()}. */ private static ImmutableMap<ClassPathEntry, ImmutableSetMultimap<SymbolProblem, String>> indexByJar(ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems) { ImmutableMap<ClassPathEntry, Collection<Entry<SymbolProblem, ClassFile>>> jarMap = Multimaps.index(symbolProblems.entries(), entry -> entry.getValue().getClassPathEntry()) .asMap(); return ImmutableMap.copyOf( Maps.transformValues( jarMap, entries -> ImmutableSetMultimap.copyOf( Multimaps.transformValues( ImmutableSetMultimap.copyOf(entries), ClassFile::getBinaryName)))); }
Example #4
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
private void startSubscriptionThread() { ListMultimap<String, TimedWatchFuture> watchers = Multimaps.synchronizedListMultimap( MultimapBuilder.linkedHashKeys().arrayListValues().build()); subscriberService = Executors.newFixedThreadPool(32); subscriber = new RedisShardSubscriber(watchers, workerSet, config.getWorkerChannel(), subscriberService); operationSubscription = new RedisShardSubscription( subscriber, /* onUnsubscribe=*/ () -> { subscriptionThread = null; if (onUnsubscribe != null) { onUnsubscribe.runInterruptibly(); } }, /* onReset=*/ this::updateWatchedIfDone, /* subscriptions=*/ subscriber::subscribedChannels, client); // use Executors... subscriptionThread = new Thread(operationSubscription); subscriptionThread.start(); }
Example #5
Source File: RemoteConfigLongPollService.java From apollo with Apache License 2.0 | 6 votes |
/** * Constructor. */ public RemoteConfigLongPollService() { m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second m_longPollingStopped = new AtomicBoolean(false); m_longPollingService = Executors.newSingleThreadExecutor( ApolloThreadFactory.create("RemoteConfigLongPollService", true)); m_longPollStarted = new AtomicBoolean(false); m_longPollNamespaces = Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create()); m_notifications = Maps.newConcurrentMap(); m_remoteNotificationMessages = Maps.newConcurrentMap(); m_responseType = new TypeToken<List<ApolloConfigNotification>>() { }.getType(); gson = new Gson(); m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); m_httpUtil = ApolloInjector.getInstance(HttpUtil.class); m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class); m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS()); }
Example #6
Source File: CheckCfgJavaValidator.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T * to a string which is used for checking for duplicates. * * @param <T> * the generic type * @param predicate * the predicate acting as a guard * @param function * returns a string for an instance of type T * @param elements * the elements to be checked * @return the duplicates */ private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) { List<T> result = Lists.newArrayList(); Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() { @Override public Collection<T> get() { return Lists.<T> newArrayList(); } }); for (final T candidate : elements) { if (predicate.apply(candidate)) { multiMap.put(function.apply(candidate), candidate); } } for (String elem : multiMap.keySet()) { final Collection<T> duplicates = multiMap.get(elem); if (duplicates.size() > 1) { result.addAll(duplicates); } } return result; }
Example #7
Source File: DefaultQueryPlanner.java From datawave with Apache License 2.0 | 6 votes |
protected Multimap<String,Type<?>> configureIndexedAndNormalizedFields(Multimap<String,Type<?>> fieldToDatatypeMap, Set<String> indexedFields, Set<String> reverseIndexedFields, Set<String> normalizedFields, ShardQueryConfiguration config, ASTJexlScript queryTree) throws DatawaveQueryException, TableNotFoundException, InstantiationException, IllegalAccessException { log.debug("config.getDatatypeFilter() = " + config.getDatatypeFilter()); log.debug("fieldToDatatypeMap.keySet() is " + fieldToDatatypeMap.keySet()); config.setIndexedFields(indexedFields); config.setReverseIndexedFields(reverseIndexedFields); log.debug("normalizedFields = " + normalizedFields); config.setQueryFieldsDatatypes(HashMultimap.create(Multimaps.filterKeys(fieldToDatatypeMap, input -> !normalizedFields.contains(input)))); log.debug("IndexedFields Datatypes: " + config.getQueryFieldsDatatypes()); config.setNormalizedFieldsDatatypes(HashMultimap.create(Multimaps.filterKeys(fieldToDatatypeMap, normalizedFields::contains))); log.debug("NormalizedFields Datatypes: " + config.getNormalizedFieldsDatatypes()); if (log.isTraceEnabled()) { log.trace("Normalizers:"); for (String field : fieldToDatatypeMap.keySet()) { log.trace(field + ": " + fieldToDatatypeMap.get(field)); } } return fieldToDatatypeMap; }
Example #8
Source File: WebsocketHandler.java From onboard with Apache License 2.0 | 6 votes |
public void sendMessage(String userEmail, String message) { Multimap<String, WebSocketSession> syncMap = Multimaps.synchronizedMultimap(userPagesMap); Collection<WebSocketSession> mis = syncMap.get(userEmail); synchronized (syncMap) { if (mis != null) { Iterator<WebSocketSession> it = mis.iterator(); while (it.hasNext()) { WebSocketSession session = it.next(); try { session.sendMessage(new TextMessage(message)); } catch (Exception e) { logger.info("The WebSocket connection has been closed: " + session.toString()); } } } } }
Example #9
Source File: AssertJGuavaUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception { final Multimap<Integer, String> mmap1 = ArrayListMultimap.create(); mmap1.put(1, "one"); mmap1.put(1, "1"); mmap1.put(2, "two"); mmap1.put(2, "2"); final Multimap<Integer, String> mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new); mmap1_clone.put(1, "one"); mmap1_clone.put(1, "1"); mmap1_clone.put(2, "two"); mmap1_clone.put(2, "2"); final Multimap<Integer, String> mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new); mmap2.put(1, "one"); mmap2.put(1, "1"); assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone); }
Example #10
Source File: MediaType.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
private String computeToString() { StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype); if (!parameters.isEmpty()) { builder.append("; "); Multimap<String, String> quotedParameters = Multimaps.transformValues( parameters, new Function<String, String>() { @Override public String apply(String value) { return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value); } }); PARAMETER_JOINER.appendTo(builder, quotedParameters.entries()); } return builder.toString(); }
Example #11
Source File: ShardCompactionManager.java From presto with Apache License 2.0 | 6 votes |
private void discoverShards() { log.info("Discovering shards that need compaction..."); Set<ShardMetadata> allShards = shardManager.getNodeShards(currentNodeIdentifier); ListMultimap<Long, ShardMetadata> tableShards = Multimaps.index(allShards, ShardMetadata::getTableId); for (Entry<Long, List<ShardMetadata>> entry : Multimaps.asMap(tableShards).entrySet()) { long tableId = entry.getKey(); if (!metadataDao.isCompactionEligible(tableId)) { continue; } List<ShardMetadata> shards = entry.getValue(); Collection<OrganizationSet> organizationSets = filterAndCreateCompactionSets(tableId, shards); log.info("Created %s organization set(s) for table ID %s", organizationSets.size(), tableId); for (OrganizationSet set : organizationSets) { organizer.enqueue(set); } } }
Example #12
Source File: AlertUtils.java From incubator-pinot with Apache License 2.0 | 6 votes |
public static Map<Long, Long> makeVectorClock(Collection<MergedAnomalyResultDTO> anomalies) { Multimap<Long, MergedAnomalyResultDTO> grouped = Multimaps.index(anomalies, new Function<MergedAnomalyResultDTO, Long>() { @Nullable @Override public Long apply(@Nullable MergedAnomalyResultDTO mergedAnomalyResultDTO) { // Return functionId to support alerting of legacy anomalies if (mergedAnomalyResultDTO.getDetectionConfigId() == null) { return mergedAnomalyResultDTO.getFunctionId(); } return mergedAnomalyResultDTO.getDetectionConfigId(); } }); Map<Long, Long> detection2max = new HashMap<>(); for (Map.Entry<Long, Collection<MergedAnomalyResultDTO>> entry : grouped.asMap().entrySet()) { detection2max.put(entry.getKey(), getLastTimeStamp(entry.getValue(), -1)); } return detection2max; }
Example #13
Source File: ListMultimapProperty.java From FreeBuilder with Apache License 2.0 | 6 votes |
private void addGetter(SourceBuilder code) { code.addLine("") .addLine("/**") .addLine(" * Returns an unmodifiable view of the multimap that will be returned by") .addLine(" * %s.", datatype.getType().javadocNoArgMethodLink(property.getGetterName())) .addLine(" * Changes to this builder will be reflected in the view.") .addLine(" */") .addLine("public %s<%s, %s> %s() {", ListMultimap.class, keyType, valueType, getter(property)) .addLine(" return %s.unmodifiableListMultimap(%s);", Multimaps.class, property.getField()) .addLine("}"); }
Example #14
Source File: ImpactAnalysisTool.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
private static Multimap<String, SecurityIndex> runImpactAnalysis(Network network, Set<String> contingencyIds, ComputationManager computationManager, SimulatorFactory simulatorFactory, ContingenciesProvider contingenciesProvider, PrintStream out) throws Exception { Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0); ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingenciesProvider); Map<String, Object> initContext = new HashMap<>(); SimulationParameters simulationParameters = SimulationParameters.load(); stabilization.init(simulationParameters, initContext); impactAnalysis.init(simulationParameters, initContext); out.println("running stabilization simulation..."); StabilizationResult sr = stabilization.run(); out.println("stabilization status: " + sr.getStatus()); out.println("stabilization metrics: " + sr.getMetrics()); if (sr.getStatus() == StabilizationStatus.COMPLETED) { out.println("running impact analysis..."); ImpactAnalysisResult iar = impactAnalysis.run(sr.getState(), contingencyIds); out.println("impact analysis metrics: " + iar.getMetrics()); return Multimaps.index(iar.getSecurityIndexes(), securityIndex -> securityIndex.getId().getContingencyId()); } return null; }
Example #15
Source File: SchedulerThriftInterface.java From attic-aurora with Apache License 2.0 | 6 votes |
private static Set<InstanceTaskConfig> buildInitialState(Map<Integer, ITaskConfig> tasks) { // Translate tasks into instance IDs. Multimap<ITaskConfig, Integer> instancesByConfig = HashMultimap.create(); Multimaps.invertFrom(Multimaps.forMap(tasks), instancesByConfig); // Reduce instance IDs into contiguous ranges. Map<ITaskConfig, Set<Range<Integer>>> rangesByConfig = Maps.transformValues(instancesByConfig.asMap(), Numbers::toRanges); ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder(); for (Map.Entry<ITaskConfig, Set<Range<Integer>>> entry : rangesByConfig.entrySet()) { builder.add(new InstanceTaskConfig() .setTask(entry.getKey().newBuilder()) .setInstances(IRange.toBuildersSet(convertRanges(entry.getValue())))); } return builder.build(); }
Example #16
Source File: CxxPreprocessables.java From buck with Apache License 2.0 | 6 votes |
/** Builds a {@link CxxPreprocessorInput} for a rule. */ public static CxxPreprocessorInput getCxxPreprocessorInput( BuildTarget buildTarget, ActionGraphBuilder graphBuilder, boolean hasHeaderSymlinkTree, CxxPlatform platform, HeaderVisibility headerVisibility, IncludeType includeType, Multimap<CxxSource.Type, String> exportedPreprocessorFlags, Iterable<FrameworkPath> frameworks) { CxxPreprocessorInput.Builder builder = CxxPreprocessorInput.builder(); if (hasHeaderSymlinkTree) { addHeaderSymlinkTree( builder, buildTarget, graphBuilder, platform, headerVisibility, includeType); } return builder .putAllPreprocessorFlags( ImmutableListMultimap.copyOf( Multimaps.transformValues(exportedPreprocessorFlags, StringArg::of))) .addAllFrameworks(frameworks) .build(); }
Example #17
Source File: _CorpusQueryAssessments.java From tac-kbp-eal with MIT License | 6 votes |
public final CorpusQueryAssessments filterForAssessment(final Set<QueryAssessment2016> assessment2016) { final ImmutableSet.Builder<QueryResponse2016> matchingQueriesB = ImmutableSet.builder(); for (final QueryResponse2016 queryResponse2016 : assessments().keySet()) { if (assessment2016.contains(assessments().get(queryResponse2016))) { matchingQueriesB.add(queryResponse2016); } } final ImmutableSet<QueryResponse2016> matchingQueries = matchingQueriesB.build(); final CorpusQueryAssessments.Builder ret = CorpusQueryAssessments.builder(); ret.queryReponses(matchingQueries); ret.putAllQueryResponsesToSystemIDs( Multimaps.filterKeys(queryResponsesToSystemIDs(), in(matchingQueries))); ret.putAllMetadata(Maps.filterKeys(metadata(), in(matchingQueries))); ret.putAllAssessments(Maps.filterKeys(assessments(), in(matchingQueries))); return ret.build(); }
Example #18
Source File: CheckJavaValidator.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T * to a string which is used for checking for duplicates. * * @param <T> * the generic type * @param predicate * the predicate acting as a guard * @param function * returns a string for an instance of type T * @param elements * the elements to be checked * @return the duplicates */ private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) { List<T> result = Lists.newArrayList(); Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() { @Override public Collection<T> get() { return Lists.<T> newArrayList(); } }); for (final T candidate : elements) { if (predicate.apply(candidate)) { multiMap.put(function.apply(candidate), candidate); } } for (String elem : multiMap.keySet()) { final Collection<T> duplicates = multiMap.get(elem); if (duplicates.size() > 1) { result.addAll(duplicates); } } return result; }
Example #19
Source File: VertexInfo.java From tez with Apache License 2.0 | 5 votes |
public final Multimap<Container, TaskAttemptInfo> getContainersMapping() { Multimap<Container, TaskAttemptInfo> containerMapping = LinkedHashMultimap.create(); for (TaskAttemptInfo attemptInfo : getTaskAttempts()) { containerMapping.put(attemptInfo.getContainer(), attemptInfo); } return Multimaps.unmodifiableMultimap(containerMapping); }
Example #20
Source File: GuavaTest.java From onetwo with Apache License 2.0 | 5 votes |
@Test public void testGroupBy(){ List<UserEntity> all = LangUtils.newArrayList(); List<UserEntity> aa = createSameNameUserList("aa", 3); List<UserEntity> bb = createSameNameUserList("bb", 1); List<UserEntity> cc = createSameNameUserList("cc", 2); all.addAll(aa); all.addAll(bb); all.addAll(cc); ImmutableListMultimap<String, UserEntity> groups = Multimaps.index(all, new Function<UserEntity, String>() { @Override public String apply(UserEntity input) { return input.getUserName(); } }); System.out.println("groups:" + groups); Assert.assertEquals(3, groups.get("aa").size()); Assert.assertEquals(1, groups.get("bb").size()); Assert.assertEquals(2, groups.get("cc").size()); Map<String, List<UserEntity>> userGroup = all.stream().collect(Collectors.groupingBy(u->u.getUserName())); System.out.println("userGroup:" + userGroup); Assert.assertEquals(3, userGroup.get("aa").size()); Assert.assertEquals(1, userGroup.get("bb").size()); Assert.assertEquals(2, userGroup.get("cc").size()); }
Example #21
Source File: StateChangeNotifier.java From tez with Apache License 2.0 | 5 votes |
public StateChangeNotifier(DAG dag) { this.dag = dag; this.vertexListeners = Multimaps.synchronizedSetMultimap( HashMultimap.<TezVertexID, ListenerContainer>create()); this.lastKnowStatesMap = LinkedListMultimap.create(); startThread(); }
Example #22
Source File: ServiceManager.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException { monitor.enter(); try { if (!monitor.waitForUninterruptibly(stoppedGuard, timeout, unit)) { throw new TimeoutException( "Timeout waiting for the services to stop. The following " + "services have not stopped: " + Multimaps.filterKeys(servicesByState, not(in(EnumSet.of(TERMINATED, FAILED))))); } } finally { monitor.leave(); } }
Example #23
Source File: MediaType.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
private String computeToString() { StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype); if (!parameters.isEmpty()) { builder.append("; "); Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters, new Function<String, String>() { @Override public String apply(String value) { return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value); } }); PARAMETER_JOINER.appendTo(builder, quotedParameters.entries()); } return builder.toString(); }
Example #24
Source File: MultimapType.java From javers with Apache License 2.0 | 5 votes |
/** * @return immutable Multimap */ @Override public Multimap map(Object sourceEnumerable, EnumerableFunction mapFunction, OwnerContext owner) { Validate.argumentIsNotNull(mapFunction); Multimap sourceMultimap = toNotNullMultimap(sourceEnumerable); Multimap targetMultimap = ArrayListMultimap.create(); MapEnumerationOwnerContext enumeratorContext = new MapEnumerationOwnerContext(owner, true); MapType.mapEntrySet(sourceMultimap.entries(), mapFunction, enumeratorContext, (k,v) -> targetMultimap.put(k,v)); return Multimaps.unmodifiableMultimap(targetMultimap); }
Example #25
Source File: GrayReleaseRulesHolder.java From apollo with Apache License 2.0 | 5 votes |
public GrayReleaseRulesHolder() { loadVersion = new AtomicLong(); grayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); reversedGrayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory .create("GrayReleaseRulesHolder", true)); }
Example #26
Source File: AnswerableExtractorAligner.java From tac-kbp-eal with MIT License | 5 votes |
/** * Generates an alignment between two collections of answers using this aligner. * * Every left and right answer will appear in the resulting alignment. All left answers and right * answers with the same answerables under the left and right answerable extraction functions will * end up aligned. */ public <LeftTrueAnswerType extends LeftAnswerType, RightTrueAnswerType extends RightAnswerType> AnswerAlignment<AnswerableType, LeftTrueAnswerType, RightTrueAnswerType> align( final Iterable<LeftTrueAnswerType> leftAnswers, final Iterable<RightTrueAnswerType> rightAnswers) { final Multimap<AnswerableType, LeftTrueAnswerType> equivClassesToLeft = Multimaps.index(leftAnswers, leftAnswerExtractor); final Multimap<AnswerableType, RightTrueAnswerType> equivClassesToRight = Multimaps.index(rightAnswers, rightAnswerExtractor); return AnswerAlignment.create(equivClassesToLeft, equivClassesToRight); }
Example #27
Source File: CycleDetectingLock.java From businessworks with Apache License 2.0 | 5 votes |
/** * Algorithm to detect a potential lock cycle. * * For lock's thread owner check which lock is it trying to take. * Repeat recursively. When current thread is found a potential cycle is detected. * * @see CycleDetectingLock#lockOrDetectPotentialLocksCycle() */ private ListMultimap<Long, ID> detectPotentialLocksCycle() { final long currentThreadId = Thread.currentThread().getId(); if (lockOwnerThreadId == null || lockOwnerThreadId == currentThreadId) { // if nobody owns this lock, lock cycle is impossible // if a current thread owns this lock, we let Guice to handle it return ImmutableListMultimap.of(); } ListMultimap<Long, ID> potentialLocksCycle = Multimaps.newListMultimap( new LinkedHashMap<Long, Collection<ID>>(), new Supplier<List<ID>>() { @Override public List<ID> get() { return Lists.newArrayList(); } }); // lock that is a part of a potential locks cycle, starts with current lock ReentrantCycleDetectingLock lockOwnerWaitingOn = this; // try to find a dependency path between lock's owner thread and a current thread while (lockOwnerWaitingOn != null && lockOwnerWaitingOn.lockOwnerThreadId != null) { Long threadOwnerThreadWaits = lockOwnerWaitingOn.lockOwnerThreadId; // in case locks cycle exists lock we're waiting for is part of it potentialLocksCycle.putAll(threadOwnerThreadWaits, getAllLockIdsAfter(threadOwnerThreadWaits, lockOwnerWaitingOn)); if (threadOwnerThreadWaits == currentThreadId) { // owner thread depends on current thread, cycle detected return potentialLocksCycle; } // going for the next thread we wait on indirectly lockOwnerWaitingOn = lockThreadIsWaitingOn.get(threadOwnerThreadWaits); } // no dependency path from an owner thread to a current thread return ImmutableListMultimap.of(); }
Example #28
Source File: TraceAttributeNameDao.java From glowroot with Apache License 2.0 | 5 votes |
@Override public Map<String, List<String>> processResultSet(ResultSet resultSet) throws Exception { ListMultimap<String, String> multimap = ArrayListMultimap.create(); while (resultSet.next()) { multimap.put(resultSet.getString(1), resultSet.getString(2)); } return Multimaps.asMap(multimap); }
Example #29
Source File: FishingPlugin.java From 07kit with GNU General Public License v3.0 | 5 votes |
@Schedule(600) public void getSpots() { if (System.currentTimeMillis() - lastCatch >= 300000) { // If we've caught nothing in the last 5 minutes reset the sample rate. sampleFishCaught = 0; } if (!isLoggedIn()) { logger.debug("Not logged in."); return; } List<Spot> validSpots = Arrays.asList(Spot.values()).stream().filter(key -> { if (skills.getBaseLevel(Skill.FISHING) < key.level) { return false; } else if (!inventory.contains(key.equipment.ids)) { return false; } return true; }).collect(Collectors.toList()); List<Npc> npcs = this.npcs.find() .hasAction(actions) .distance(20) .asList(); spots = Multimaps.index(npcs, npc -> { for (Spot spot : validSpots) { Set<String> spotActions = new HashSet<>(Arrays.asList(spot.actions)); Set<String> npcActions = new HashSet<>(Arrays.asList(npc.getComposite().getActions())); npcActions.remove(null); if (spotActions.equals(npcActions)) { return spot; } } return Spot.UNKNOWN; }); active = inventory.contains(equipments) || equipment.contains(equipments); }
Example #30
Source File: FlowDocumentation.java From nomulus with Apache License 2.0 | 5 votes |
/** * Creates a FlowDocumentation for this flow class using data from javadoc tags. Not public * because clients should get FlowDocumentation objects via the DocumentationGenerator class. */ protected FlowDocumentation(ClassDoc flowDoc) { name = flowDoc.name(); qualifiedName = flowDoc.qualifiedName(); packageName = flowDoc.containingPackage().name(); classDocs = flowDoc.commentText(); errors = new ArrayList<>(); // Store error codes in sorted order, and leave reasons in insert order. errorsByCode = Multimaps.newListMultimap(new TreeMap<Long, Collection<ErrorCase>>(), ArrayList::new); parseTags(flowDoc); }