下面列出了java.util.concurrent.ConcurrentHashMap#newKeySet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Initializes the ACL objects and preemptively calculates all permissions for all sids.
*
* @param globalRoles set of roles from which to calculate the permissions.
*/
public GlobalAclImpl(Set<GlobalRole> globalRoles) {
for (GlobalRole role : globalRoles) {
Set<Permission> impliedPermissions = ConcurrentHashMap.newKeySet();
role.getPermissionsUnsorted().parallelStream().map(PermissionWrapper::getPermission).forEach(impliedPermissions::add);
role.getSids().parallelStream().forEach(sid -> {
Set<Permission> permissionsForSid = permissionList.get(sid);
if (permissionsForSid == null) {
permissionsForSid = new HashSet<>();
}
permissionsForSid.addAll(impliedPermissions);
permissionList.put(sid, permissionsForSid);
});
}
}
/**
* KeySet.iterator() returns an iterator containing the elements of the
* set
*/
public void testIterator() {
Collection empty = ConcurrentHashMap.newKeySet();
int size = 20;
assertFalse(empty.iterator().hasNext());
try {
empty.iterator().next();
shouldThrow();
} catch (NoSuchElementException success) {}
Integer[] elements = new Integer[size];
for (int i = 0; i < size; i++)
elements[i] = i;
Collections.shuffle(Arrays.asList(elements));
Collection<Integer> full = populatedSet(elements);
Iterator it = full.iterator();
for (int j = 0; j < size; j++) {
assertTrue(it.hasNext());
it.next();
}
assertIteratorExhausted(it);
}
public static void updateFrozenEdge(BalanceList frozenEdgeList) {
if (frozenEdgeList != null) {
for (int i = numberOfRecentLists - 1; i > 0; i--) {
recentLists[i] = recentLists[i - 1];
}
recentLists[0] = frozenEdgeList;
Set<ByteBuffer> accountsInSystem = ConcurrentHashMap.newKeySet();
for (BalanceListItem item : frozenEdgeList.getItems()) {
accountsInSystem.add(ByteBuffer.wrap(item.getIdentifier()));
}
BalanceListManager.accountsInSystem = accountsInSystem;
balanceListMap.clear();
balanceListMap.put(ByteBuffer.wrap(frozenEdgeList.getHash()), frozenEdgeList);
}
}
public MetadataConsumer(IMetadataService metadataService,
TorrentId torrentId,
Config config) {
this.peersWithoutMetadata = new ConcurrentHashMap<>();
this.supportingPeers = ConcurrentHashMap.newKeySet();
this.requestedFirstPeers = new ConcurrentHashMap<>();
this.requestedAllPeers = ConcurrentHashMap.newKeySet();
this.metadataService = metadataService;
this.torrentId = Objects.requireNonNull(torrentId);
this.torrent = new AtomicReference<>();
this.metadataExchangeBlockSize = config.getMetadataExchangeBlockSize();
this.metadataExchangeMaxSize = config.getMetadataExchangeMaxSize();
}
public EmoteImpl(long id, GuildImpl guild, boolean fake)
{
this.id = id;
this.api = guild.getJDA();
this.guild = new SnowflakeReference<>(guild, api::getGuildById);
this.roles = ConcurrentHashMap.newKeySet();
this.fake = fake;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
public void addActionProvider(AnnotatedActions actionProvider, Map<String, Object> properties) {
Collection<ModuleInformation> moduleInformations = helper.parseAnnotations(actionProvider);
String configName = getConfigNameFromService(properties);
for (ModuleInformation mi : moduleInformations) {
mi.setConfigName(configName);
ModuleType oldType = null;
if (this.moduleInformation.containsKey(mi.getUID())) {
oldType = helper.buildModuleType(mi.getUID(), this.moduleInformation);
Set<ModuleInformation> availableModuleConfigs = this.moduleInformation.get(mi.getUID());
availableModuleConfigs.add(mi);
} else {
Set<ModuleInformation> configs = ConcurrentHashMap.newKeySet();
configs.add(mi);
this.moduleInformation.put(mi.getUID(), configs);
}
ModuleType mt = helper.buildModuleType(mi.getUID(), this.moduleInformation);
if (mt != null) {
for (ProviderChangeListener<ModuleType> l : changeListeners) {
if (oldType != null) {
l.updated(this, oldType, mt);
} else {
l.added(this, mt);
}
}
}
}
}
/**
* Add an entry to the dnsToUuidMap, which maps hostname / IP to the DNs
* running on that host. As each address can have many DNs running on it,
* this is a one to many mapping.
* @param dnsName String representing the hostname or IP of the node
* @param uuid String representing the UUID of the registered node.
*/
private synchronized void addEntryTodnsToUuidMap(
String dnsName, String uuid) {
Set<String> dnList = dnsToUuidMap.get(dnsName);
if (dnList == null) {
dnList = ConcurrentHashMap.newKeySet();
dnsToUuidMap.put(dnsName, dnList);
}
dnList.add(uuid);
}
private Set<AnnounceKey> getOrCreateExtraAnnounceKeys(TorrentId torrentId) {
Set<AnnounceKey> announceKeys = extraAnnounceKeys.get(torrentId);
if (announceKeys == null) {
announceKeys = ConcurrentHashMap.newKeySet();
Set<AnnounceKey> existing = extraAnnounceKeys.putIfAbsent(torrentId, announceKeys);
if (existing != null) {
announceKeys = existing;
}
}
return announceKeys;
}
@Test
void putMissingNestedProductType_WithIdenticalOneReferencingAttrToAnEmptyMap_ShouldOverwriteExisting() {
// preparation
final ConcurrentHashMap<String,
ConcurrentHashMap<String, ConcurrentHashMap.KeySetView<AttributeDefinitionDraft, Boolean>>>
missingProductTypeReferences = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, ConcurrentHashMap.KeySetView<AttributeDefinitionDraft, Boolean>>
productTypesReferencingMissing1 = new ConcurrentHashMap<>();
final AttributeDefinitionDraft referencingAttributeDefinitionDraft = AttributeDefinitionDraftBuilder
.of(NestedAttributeType.of(
ProductType.referenceOfId("missingPT")), "attr-name", ofEnglish("label"), true)
.build();
final ConcurrentHashMap.KeySetView<AttributeDefinitionDraft, Boolean> definitionDrafts =
ConcurrentHashMap.newKeySet();
definitionDrafts.add(referencingAttributeDefinitionDraft);
productTypesReferencingMissing1.put("referencingPT", definitionDrafts);
missingProductTypeReferences.put("missingPT", productTypesReferencingMissing1);
final ProductTypeSyncStatistics productTypeSyncStatistics =
new ProductTypeSyncStatistics(missingProductTypeReferences);
// test
productTypeSyncStatistics.putMissingNestedProductType("missingPT",
"referencingPT",
referencingAttributeDefinitionDraft);
// assertion
assertThat(productTypeSyncStatistics.getProductTypeKeysWithMissingParents()).hasSize(1);
assertThat(productTypeSyncStatistics.getProductTypeKeysWithMissingParents().get("missingPT")).hasSize(1);
assertThat(productTypeSyncStatistics.getProductTypeKeysWithMissingParents()
.get("missingPT")
.get("referencingPT"))
.contains(referencingAttributeDefinitionDraft);
}
@Autowired
public EventSourceSyncDurationLogger(final Optional<List<EventSource>> eventSources) {
allChannels = eventSources.orElse(Collections.emptyList())
.stream()
.map(EventSource::getChannelName)
.collect(toSet());
healthyChannels = ConcurrentHashMap.newKeySet();
}
@Ignore("This is currently unstable as if the clear does not complete before the failover," +
"there is no future operation that will trigger the code in ClusterTierActiveEntity.invokeServerStoreOperation" +
"dealing with in-flight invalidation reconstructed from reconnect data")
@Test(timeout=180000)
public void testClear() throws Exception {
List<Future<?>> futures = new ArrayList<>();
Set<Long> universalSet = ConcurrentHashMap.newKeySet();
caches.forEach(cache -> {
for (int i = 0; i < NUM_OF_THREADS; i++) {
Map<Long, BlobValue> map = random.longs().limit(JOB_SIZE).collect(HashMap::new, (hashMap, x) -> hashMap.put(x, new BlobValue()), HashMap::putAll);
futures.add(executorService.submit(() -> {
cache.putAll(map);
universalSet.addAll(map.keySet());
}));
}
});
drainTasks(futures);
universalSet.forEach(x -> {
cache1.get(x);
cache2.get(x);
});
Future<?> clearFuture = executorService.submit(() -> cache1.clear());
CLUSTER.getClusterControl().waitForRunningPassivesInStandby();
CLUSTER.getClusterControl().terminateActive();
clearFuture.get();
universalSet.forEach(x -> assertThat(cache2.get(x), nullValue()));
}
static Set<Integer> populatedSet(int n) {
Set<Integer> a = ConcurrentHashMap.<Integer>newKeySet();
assertTrue(a.isEmpty());
for (int i = 0; i < n; i++)
assertTrue(a.add(i));
assertEquals(n == 0, a.isEmpty());
assertEquals(n, a.size());
return a;
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
protected static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
@Test
public void test() {
JavaFileObject javaFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoValue;",
"",
"@AutoValue",
"public abstract class Baz {",
" public static Baz create() {",
" return new AutoValue_Baz();",
" }",
"}");
JavaFileObject expectedOutput =
JavaFileObjects.forSourceLines(
"foo.bar.AutoValue_Baz",
"package foo.bar;",
"",
"final class AutoValue_Baz extends Baz {",
" AutoValue_Baz() {",
" }",
"",
" @Override public String toString() {",
" return \"Baz{\"",
" + \"}\";",
" }",
"",
" @Override public boolean equals(Object o) {",
" if (o == this) {",
" return true;",
" }",
" if (o instanceof Baz) {",
" return true;",
" }",
" return false;",
" }",
"",
" @Override public int hashCode() {",
" int h$ = 1;",
" return h$;",
" }",
"}");
Set<String> ignoredGenerated = ConcurrentHashMap.newKeySet();
Processor autoValueProcessor = new AutoValueProcessor();
ProcessorHandler handler = new ProcessorHandler(autoValueProcessor, ignoredGenerated);
Processor noGeneratedProcessor = partialProxy(Processor.class, handler);
Compilation compilation =
javac()
.withOptions(javacOptions)
.withProcessors(noGeneratedProcessor)
.compile(javaFileObject);
assertThat(compilation).succeededWithoutWarnings();
assertThat(compilation)
.generatedSourceFile("foo.bar.AutoValue_Baz")
.hasSourceEquivalentTo(expectedOutput);
assertThat(ignoredGenerated).containsExactly(expectedAnnotation);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
public ServerStateNode(ServerName serverName) {
this.serverName = serverName;
this.regions = ConcurrentHashMap.newKeySet();
}
/**
* Tests that all slots are being returned to the {@link SlotOwner} if the
* {@link ExecutionGraph} is being cancelled. See FLINK-9908
*/
@Test
public void testCancellationOfIncompleteScheduling() throws Exception {
final int parallelism = 10;
final JobVertex jobVertex = new JobVertex("Test job vertex");
jobVertex.setInvokableClass(NoOpInvokable.class);
jobVertex.setParallelism(parallelism);
final JobGraph jobGraph = new JobGraph(jobVertex);
jobGraph.setAllowQueuedScheduling(true);
jobGraph.setScheduleMode(ScheduleMode.EAGER);
final TestingSlotOwner slotOwner = new TestingSlotOwner();
final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway();
final ConcurrentMap<SlotRequestId, Integer> slotRequestIds = new ConcurrentHashMap<>(parallelism);
final TestingSlotProvider slotProvider = new TestingSlotProvider(
(SlotRequestId slotRequestId) -> {
slotRequestIds.put(slotRequestId, 1);
// return 50/50 fulfilled and unfulfilled requests
return slotRequestIds.size() % 2 == 0 ?
CompletableFuture.completedFuture(
createSingleLogicalSlot(slotOwner, taskManagerGateway, slotRequestId)) :
new CompletableFuture<>();
});
final ExecutionGraph executionGraph = createExecutionGraph(jobGraph, slotProvider);
executionGraph.start(ComponentMainThreadExecutorServiceAdapter.forMainThread());
final Set<SlotRequestId> slotRequestIdsToReturn = ConcurrentHashMap.newKeySet(slotRequestIds.size());
executionGraph.scheduleForExecution();
slotRequestIdsToReturn.addAll(slotRequestIds.keySet());
slotOwner.setReturnAllocatedSlotConsumer(logicalSlot -> {
slotRequestIdsToReturn.remove(logicalSlot.getSlotRequestId());
});
slotProvider.setSlotCanceller(slotRequestIdsToReturn::remove);
// make sure that we complete cancellations of deployed tasks
taskManagerGateway.setCancelConsumer(
(ExecutionAttemptID executionAttemptId) -> {
final Execution execution = executionGraph.getRegisteredExecutions().get(executionAttemptId);
// if the execution was cancelled in state SCHEDULING, then it might already have been removed
if (execution != null) {
execution.completeCancelling();
}
}
);
executionGraph.cancel();
assertThat(slotRequestIdsToReturn, is(empty()));
}
public JobCounter(int batchSize) {
this.jobs = new AtomicInteger(0);
this.elements = ConcurrentHashMap.newKeySet();
this.indexes = ConcurrentHashMap.newKeySet();
this.batchSize = batchSize;
}
/**
* Registeres the Learner for processing by SendWorker.
*/
@OnOpen
public void registerUser(Session websocket) throws IOException {
Long lessonId = Long.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0));
String login = websocket.getUserPrincipal().getName();
User user = PresenceWebsocketServer.getUserManagementService().getUserByLogin(login);
String nickname = user.getFirstName() + " " + user.getLastName();
websocket.getUserProperties().put(PARAM_NICKNAME, nickname);
websocket.getUserProperties().put(AttributeNames.PARAM_LESSON_ID, lessonId);
PresenceWebsocketServer.getSecurityService().isLessonParticipant(lessonId, user.getUserId(), "join lesson chat",
true);
Set<Session> lessonWebsockets = PresenceWebsocketServer.websockets.get(lessonId);
if (lessonWebsockets == null) {
lessonWebsockets = ConcurrentHashMap.newKeySet();
PresenceWebsocketServer.websockets.put(lessonId, lessonWebsockets);
}
lessonWebsockets.add(websocket);
Roster roster = PresenceWebsocketServer.rosters.get(lessonId);
if (roster == null) {
Lesson lesson = PresenceWebsocketServer.getLessonService().getLesson(lessonId);
// build a new roster object
roster = new Roster(lessonId, lesson.getLearnerImAvailable());
PresenceWebsocketServer.rosters.put(lessonId, roster);
}
new Thread(() -> {
try {
// websocket communication bypasses standard HTTP filters, so Hibernate session needs to be initialised manually
HibernateSessionManager.openSession();
SendWorker.send(lessonId, nickname);
} finally {
HibernateSessionManager.closeSession();
}
}).start();
if (PresenceWebsocketServer.log.isDebugEnabled()) {
PresenceWebsocketServer.log
.debug("User " + nickname + " entered Presence Chat with lesson ID: " + lessonId);
}
}