Java Code Examples for java.util.concurrent.ConcurrentHashMap#newKeySet()

The following examples show how to use java.util.concurrent.ConcurrentHashMap#newKeySet() . 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: GlobalAclImpl.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
/**
 * 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);
        });
    }
}
 
Example 2
Source File: ConcurrentHashMap8Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: BalanceListManager.java    From nyzoVerifier with The Unlicense 6 votes vote down vote up
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);
        }
    }
 
Example 4
Source File: MetadataConsumer.java    From bt with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 5
Source File: AnnotatedActionModuleTypeProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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);
                }
            }
        }
    }
}
 
Example 6
Source File: ConcurrentHashMap8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: BasicClusteredCacheOpsReplicationMultiThreadedTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@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()));

}
 
Example 8
Source File: EventSourceSyncDurationLogger.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Autowired
public EventSourceSyncDurationLogger(final Optional<List<EventSource>> eventSources) {
    allChannels = eventSources.orElse(Collections.emptyList())
            .stream()
            .map(EventSource::getChannelName)
            .collect(toSet());
    healthyChannels = ConcurrentHashMap.newKeySet();
}
 
Example 9
Source File: ProductTypeSyncStatisticsTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: PeerRegistry.java    From bt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: MockNodeManager.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 12
Source File: EmoteImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: ServerStateNode.java    From hbase with Apache License 2.0 4 votes vote down vote up
public ServerStateNode(ServerName serverName) {
  this.serverName = serverName;
  this.regions = ConcurrentHashMap.newKeySet();
}
 
Example 14
Source File: HistoryQuickSearchPm.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
	Set<Object> seen = ConcurrentHashMap.newKeySet();
	return t -> seen.add(keyExtractor.apply(t));
}
 
Example 15
Source File: GeneratedDoesNotExistTest.java    From auto with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 16
Source File: ExecutionGraphSchedulingTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * 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()));
}
 
Example 17
Source File: JobCounters.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
public JobCounter(int batchSize) {
    this.jobs = new AtomicInteger(0);
    this.elements = ConcurrentHashMap.newKeySet();
    this.indexes = ConcurrentHashMap.newKeySet();
    this.batchSize = batchSize;
}
 
Example 18
Source File: EmbeddedPostgresContextCustomizerFactory.java    From embedded-database-spring-test with Apache License 2.0 4 votes vote down vote up
protected static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}
 
Example 19
Source File: PresenceWebsocketServer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * 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);
}
   }
 
Example 20
Source File: LambdaUtils.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}