Java Code Examples for java.util.Collections.newSetFromMap()

The following are Jave code examples for showing how to use newSetFromMap() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop-oss   File: Server.java   View Source Code Vote up 6 votes
ConnectionManager() {
  this.idleScanTimer = new Timer(
      "IPC Server idle connection scanner for port " + getPort(), true);
  this.idleScanThreshold = conf.getInt(
      CommonConfigurationKeysPublic.IPC_CLIENT_IDLETHRESHOLD_KEY,
      CommonConfigurationKeysPublic.IPC_CLIENT_IDLETHRESHOLD_DEFAULT);
  this.idleScanInterval = conf.getInt(
      CommonConfigurationKeys.IPC_CLIENT_CONNECTION_IDLESCANINTERVAL_KEY,
      CommonConfigurationKeys.IPC_CLIENT_CONNECTION_IDLESCANINTERVAL_DEFAULT);
  this.maxIdleTime = 2 * conf.getInt(
      CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_KEY,
      CommonConfigurationKeysPublic.IPC_CLIENT_CONNECTION_MAXIDLETIME_DEFAULT);
  this.maxIdleToClose = conf.getInt(
      CommonConfigurationKeysPublic.IPC_CLIENT_KILL_MAX_KEY,
      CommonConfigurationKeysPublic.IPC_CLIENT_KILL_MAX_DEFAULT);
  this.maxConnections = conf.getInt(
      CommonConfigurationKeysPublic.IPC_SERVER_MAX_CONNECTIONS_KEY,
      CommonConfigurationKeysPublic.IPC_SERVER_MAX_CONNECTIONS_DEFAULT);
  // create a set with concurrency -and- a thread-safe iterator, add 2
  // for listener and idle closer threads
  this.connections = Collections.newSetFromMap(
      new ConcurrentHashMap<Connection,Boolean>(
          maxQueueSize, 0.75f, readThreads+2));
}
 
Example 2
Project: L2J-Global   File: L2Character.java   View Source Code Vote up 6 votes
/**
 * Adds the abnormal visual and sends packet for updating them in client.
 * @param aves the abnormal visual effects
 */
public final void startAbnormalVisualEffect(AbnormalVisualEffect... aves)
{
	for (AbnormalVisualEffect ave : aves)
	{
		if (_abnormalVisualEffects == null)
		{
			synchronized (this)
			{
				if (_abnormalVisualEffects == null)
				{
					_abnormalVisualEffects = Collections.newSetFromMap(new ConcurrentHashMap<>());
				}
			}
		}
		_abnormalVisualEffects.add(ave);
	}
	resetCurrentAbnormalVisualEffects();
}
 
Example 3
Project: hibernate-ogm-ignite   File: IgniteTestHelper.java   View Source Code Vote up 6 votes
@Override
public long getNumberOfAssociations(SessionFactory sessionFactory, AssociationStorageType type) {
	int asscociationCount = 0;
	Set<IgniteCache<Object, BinaryObject>> processedCaches = Collections.newSetFromMap( new IdentityHashMap<IgniteCache<Object, BinaryObject>, Boolean>() );

	for ( CollectionPersister collectionPersister : ( (SessionFactoryImplementor) sessionFactory ).getCollectionPersisters().values() ) {
		AssociationKeyMetadata associationKeyMetadata = ( (OgmCollectionPersister) collectionPersister ).getAssociationKeyMetadata();
		IgniteCache<Object, BinaryObject> associationCache = getAssociationCache( sessionFactory, associationKeyMetadata );
		if ( !processedCaches.contains( associationCache ) ) {
			asscociationCount += associationCache.size();
			processedCaches.add( associationCache );
		}
	}

	return asscociationCount;
}
 
Example 4
Project: iTAP-controller   File: DeviceMultiIndex.java   View Source Code Vote up 6 votes
@Override
public boolean updateIndex(Entity entity, Long deviceKey) {
    Collection<Long> devices = null;

    IndexedEntity ie = new IndexedEntity(keyFields, entity);
    if (!ie.hasNonNullKeys()) return false;

    devices = index.get(ie);
    if (devices == null) {
        Map<Long,Boolean> chm = new ConcurrentHashMap<Long,Boolean>();
        devices = Collections.newSetFromMap(chm);
        Collection<Long> r = index.putIfAbsent(ie, devices);
        if (r != null)
            devices = r;
    }
    
    devices.add(deviceKey);
    return true;
}
 
Example 5
Project: alfresco-repository   File: FeedCleaner.java   View Source Code Vote up 6 votes
public void beforeDeleteNodePerson(NodeRef personNodeRef)
{
    String userId = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_USERNAME);
    //MNT-9104 If username contains uppercase letters the action of joining a site will not be displayed in "My activities" 
    if (! userNamesAreCaseSensitive)
    {
        userId = userId.toLowerCase();
    }
    Set<String> deletedUserIds = (Set<String>)AlfrescoTransactionSupport.getResource(KEY_DELETED_USER_IDS);
    if (deletedUserIds == null)
    {
        deletedUserIds = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); // Java 6
        AlfrescoTransactionSupport.bindResource(KEY_DELETED_USER_IDS, deletedUserIds);
    }
    
    deletedUserIds.add(userId);
    
    AlfrescoTransactionSupport.bindListener(deletePersonTransactionListener);
}
 
Example 6
Project: tomcat7   File: WsServerContainer.java   View Source Code Vote up 5 votes
private void registerAuthenticatedSession(WsSession wsSession,
        String httpSessionId) {
    Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
    if (wsSessions == null) {
        wsSessions = Collections.newSetFromMap(
                 new ConcurrentHashMap<WsSession,Boolean>());
         authenticatedSessions.putIfAbsent(httpSessionId, wsSessions);
         wsSessions = authenticatedSessions.get(httpSessionId);
    }
    wsSessions.add(wsSession);
}
 
Example 7
Project: hadoop   File: BlockPoolSliceStorage.java   View Source Code Vote up 5 votes
BlockPoolSliceStorage(int namespaceID, String bpID, long cTime,
    String clusterId) {
  super(NodeType.DATA_NODE);
  this.namespaceID = namespaceID;
  this.blockpoolID = bpID;
  this.cTime = cTime;
  this.clusterID = clusterId;
  storagesWithRollingUpgradeMarker = Collections.newSetFromMap(
      new ConcurrentHashMap<String, Boolean>());
  storagesWithoutRollingUpgradeMarker = Collections.newSetFromMap(
      new ConcurrentHashMap<String, Boolean>());
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: CustomObjectInputStream.java   View Source Code Vote up 5 votes
/**
 * Construct a new instance of CustomObjectInputStream with filtering of
 * deserialized classes.
 *
 * @param stream The input stream we will read from
 * @param classLoader The class loader used to instantiate objects
 * @param log The logger to use to report any issues. It may only be null if
 *            the filterMode does not require logging
 * @param allowedClassNamePattern The regular expression to use to filter
 *                                deserialized classes. The fully qualified
 *                                class name must match this pattern for
 *                                deserialization to be allowed if filtering
 *                                is enabled.
 * @param warnOnFailure Should any failures be logged?
 *
 * @exception IOException if an input/output error occurs
 */
public CustomObjectInputStream(InputStream stream, ClassLoader classLoader,
        Log log, Pattern allowedClassNamePattern, boolean warnOnFailure)
        throws IOException {
    super(stream);
    if (log == null && allowedClassNamePattern != null && warnOnFailure) {
        throw new IllegalArgumentException(
                sm.getString("customObjectInputStream.logRequired"));
    }
    this.classLoader = classLoader;
    this.log = log;
    this.allowedClassNamePattern = allowedClassNamePattern;
    if (allowedClassNamePattern == null) {
        this.allowedClassNameFilter = null;
    } else {
        this.allowedClassNameFilter = allowedClassNamePattern.toString();
    }
    this.warnOnFailure = warnOnFailure;

    Set<String> reportedClasses;
    synchronized (reportedClassCache) {
        reportedClasses = reportedClassCache.get(classLoader);
        if (reportedClasses == null) {
            reportedClasses = Collections.newSetFromMap(new ConcurrentHashMap<String,Boolean>());
            reportedClassCache.put(classLoader, reportedClasses);
        }
    }
    this.reportedClasses = reportedClasses;
}
 
Example 9
Project: Matcher   File: Matcher.java   View Source Code Vote up 5 votes
private static <T> void sanitizeMatches(Map<T, T> matches) {
	Set<T> matched = Collections.newSetFromMap(new IdentityHashMap<>(matches.size()));
	Set<T> conflictingMatches = Collections.newSetFromMap(new IdentityHashMap<>());

	for (T cls : matches.values()) {
		if (!matched.add(cls)) {
			conflictingMatches.add(cls);
		}
	}

	if (!conflictingMatches.isEmpty()) {
		matches.values().removeAll(conflictingMatches);
	}
}
 
Example 10
Project: incubator-netbeans   File: ProjectHooks.java   View Source Code Vote up 5 votes
@Override
public void classPathsChange(AbstractClassPathProvider.ClassPathsChangeEvent event) {
    final Map<String,Set<ClassPath>> snapshot = new HashMap<>();
    for (String cpType : event.getChangedClassPathTypes()) {
        if (classPathTypes.contains(cpType)) {
            final ClassPath[] cps = cpProvider.getProjectClassPaths(cpType);
            final Set<ClassPath> newCps = Collections.newSetFromMap(new IdentityHashMap<>());
            Collections.addAll(newCps, cps);
            snapshot.put(cpType, newCps);
        }
    }
    if (!snapshot.isEmpty()) {
        updateClassPathCache(snapshot);
    }
}
 
Example 11
Project: hibernate-ogm-ignite   File: IgniteTestHelper.java   View Source Code Vote up 5 votes
@Override
public long getNumberOfEntities(SessionFactory sessionFactory) {
	int entityCount = 0;
	Set<IgniteCache<?, ?>> processedCaches = Collections.newSetFromMap( new IdentityHashMap<IgniteCache<?, ?>, Boolean>() );
	for ( EntityPersister entityPersister : ( (SessionFactoryImplementor) sessionFactory ).getEntityPersisters().values() ) {
		IgniteCache<?, ?> entityCache = getEntityCache( sessionFactory, ( (OgmEntityPersister) entityPersister ).getEntityKeyMetadata() );
		if ( !processedCaches.contains( entityCache ) ) {
			entityCount += entityCache.size( CachePeekMode.ALL );
			processedCaches.add( entityCache );
		}
	}
	return entityCount;
}
 
Example 12
Project: incubator-netbeans   File: NbActiveDocumentProvider.java   View Source Code Vote up 5 votes
@Override
public Set<? extends Document> getActiveDocuments() {
    final Set<Document> res = Collections.newSetFromMap(new IdentityHashMap<Document, Boolean>());
    for (JTextComponent jtc : EditorRegistry.componentList()) {
        final Document doc = jtc.getDocument();
        if (doc != null) {
            res.add(doc);
        }
    }
    return res;
}
 
Example 13
Project: hadoop-oss   File: Configuration.java   View Source Code Vote up 5 votes
/**
 * Get the set of parameters marked final.
 *
 * @return final parameter set.
 */
public Set<String> getFinalParameters() {
  Set<String> setFinalParams = Collections.newSetFromMap(
      new ConcurrentHashMap<String, Boolean>());
  setFinalParams.addAll(finalParameters);
  return setFinalParams;
}
 
Example 14
Project: hadoop   File: Groups.java   View Source Code Vote up 5 votes
public Groups(Configuration conf, final Timer timer) {
  impl = 
    ReflectionUtils.newInstance(
        conf.getClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, 
                      ShellBasedUnixGroupsMapping.class, 
                      GroupMappingServiceProvider.class), 
        conf);

  cacheTimeout = 
    conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 
        CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS_DEFAULT) * 1000;
  negativeCacheTimeout =
    conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS,
        CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS_DEFAULT) * 1000;
  warningDeltaMs =
    conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_WARN_AFTER_MS,
      CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_WARN_AFTER_MS_DEFAULT);
  staticUserToGroupsMap = parseStaticMapping(conf);

  this.timer = timer;
  this.cache = CacheBuilder.newBuilder()
    .refreshAfterWrite(cacheTimeout, TimeUnit.MILLISECONDS)
    .ticker(new TimerToTickerAdapter(timer))
    .expireAfterWrite(10 * cacheTimeout, TimeUnit.MILLISECONDS)
    .build(new GroupCacheLoader());

  if(negativeCacheTimeout > 0) {
    Cache<String, Boolean> tempMap = CacheBuilder.newBuilder()
      .expireAfterWrite(negativeCacheTimeout, TimeUnit.MILLISECONDS)
      .ticker(new TimerToTickerAdapter(timer))
      .build();
    negativeCache = Collections.newSetFromMap(tempMap.asMap());
  }

  if(LOG.isDebugEnabled())
    LOG.debug("Group mapping impl=" + impl.getClass().getName() + 
        "; cacheTimeout=" + cacheTimeout + "; warningDeltaMs=" +
        warningDeltaMs);
}
 
Example 15
Project: hadoop   File: BlockPoolSliceStorage.java   View Source Code Vote up 5 votes
private BlockPoolSliceStorage() {
  super(NodeType.DATA_NODE);
  storagesWithRollingUpgradeMarker = Collections.newSetFromMap(
      new ConcurrentHashMap<String, Boolean>());
  storagesWithoutRollingUpgradeMarker = Collections.newSetFromMap(
      new ConcurrentHashMap<String, Boolean>());
}
 
Example 16
Project: hadoop-oss   File: Configuration.java   View Source Code Vote up 5 votes
/** 
 * A new configuration with the same settings cloned from another.
 * 
 * @param other the configuration from which to clone settings.
 */
@SuppressWarnings("unchecked")
public Configuration(Configuration other) {
 this.resources = (ArrayList<Resource>) other.resources.clone();
 synchronized(other) {
   if (other.properties != null) {
     this.properties = (Properties)other.properties.clone();
   }

   if (other.overlay!=null) {
     this.overlay = (Properties)other.overlay.clone();
   }

   this.updatingResource = new ConcurrentHashMap<String, String[]>(
       other.updatingResource);
   this.finalParameters = Collections.newSetFromMap(
       new ConcurrentHashMap<String, Boolean>());
   this.finalParameters.addAll(other.finalParameters);
 }
 
  synchronized(Configuration.class) {
    REGISTRY.put(this, null);
  }
  this.classLoader = other.classLoader;
  this.loadDefaults = other.loadDefaults;
  setQuietMode(other.getQuietMode());
}
 
Example 17
Project: iTAP-controller   File: LinkDiscoveryManager.java   View Source Code Vote up 4 votes
@Override
public void init(FloodlightModuleContext context)
		throws FloodlightModuleException {
	floodlightProviderService = context.getServiceImpl(IFloodlightProviderService.class);
	switchService = context.getServiceImpl(IOFSwitchService.class);
	storageSourceService = context.getServiceImpl(IStorageSourceService.class);
	threadPoolService = context.getServiceImpl(IThreadPoolService.class);
	restApiService = context.getServiceImpl(IRestApiService.class);
	debugCounterService = context.getServiceImpl(IDebugCounterService.class);
	debugEventService = context.getServiceImpl(IDebugEventService.class);
	shutdownService = context.getServiceImpl(IShutdownService.class);

	// read our config options
	Map<String, String> configOptions = context.getConfigParams(this);
	try {
		String histSize = configOptions.get("eventhistorysize");
		if (histSize != null) {
			EVENT_HISTORY_SIZE = Short.parseShort(histSize);
		}
	} catch (NumberFormatException e) {
		log.warn("Error event history size, using default of {} seconds", EVENT_HISTORY_SIZE);
	}
	log.debug("Event history size set to {}", EVENT_HISTORY_SIZE);

	// Set the autoportfast feature to false.
	this.autoPortFastFeature = AUTOPORTFAST_DEFAULT;

	// We create this here because there is no ordering guarantee
	this.linkDiscoveryAware = new ArrayList<ILinkDiscoveryListener>();
	this.lock = new ReentrantReadWriteLock();
	this.updates = new LinkedBlockingQueue<LDUpdate>();
	this.links = new HashMap<Link, LinkInfo>();
	this.portLinks = new HashMap<NodePortTuple, Set<Link>>();
	this.suppressLinkDiscovery = Collections.synchronizedSet(new HashSet<NodePortTuple>());
	this.switchLinks = new HashMap<DatapathId, Set<Link>>();
	this.quarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
	this.maintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();
	this.toRemoveFromQuarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
	this.toRemoveFromMaintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();

	this.ignoreMACSet = Collections.newSetFromMap(
			new ConcurrentHashMap<MACRange,Boolean>());
	this.haListener = new HAListenerDelegate();
	registerLinkDiscoveryDebugCounters();
	registerLinkDiscoveryDebugEvents();
}
 
Example 18
Project: otus_java_2017_04   File: ChatWebSocketCreator.java   View Source Code Vote up 4 votes
public ChatWebSocketCreator() {
    this.users = Collections.newSetFromMap(new ConcurrentHashMap<ChatWebSocket, Boolean>());
    System.out.println("WebSocketCreator created");
}
 
Example 19
Project: loom   File: Kmeans.java   View Source Code Vote up 4 votes
public Mean() {
    x = 0;
    y = 0;
    set = Collections.newSetFromMap(new ConcurrentHashMap<Observation, Boolean>());
}
 
Example 20
Project: googles-monorepo-demo   File: Sets.java   View Source Code Vote up 2 votes
/**
 * Creates a thread-safe set backed by a hash map. The set is backed by a
 * {@link ConcurrentHashMap} instance, and thus carries the same concurrency
 * guarantees.
 *
 * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
 * used as an element. The set is serializable.
 *
 * @return a new, empty thread-safe {@code Set}
 * @since 15.0
 */
public static <E> Set<E> newConcurrentHashSet() {
  return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}